您的位置:首页 > 其它

【LeetCode】693. Binary Number with Alternating Bits 解题报告

2018-01-17 20:59 555 查看

【LeetCode】693. Binary Number with Alternating Bits 解题报告

标签(空格分隔): LeetCode

题目地址:https://leetcode.com/problems/binary-number-with-alternating-bits/description/

题目描述:

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.

Example 1:

Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101


Example 2:

Input: 7
Output: False
Explanation:
The binary representation of 7 is: 111.


Example 3:

Input: 11
Output: False
Explanation:
The binary representation of 11 is: 1011.


Example 4:

Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.


Ways

方法一:

想法很朴素,判断二进制数任意两个字符是否是不同的即可。

可以用相加为1来判断,也可以直接用不等来判断。

class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
bin_n = bin(n)[2:]
return all(int(bin_n[i]) + int(bin_n[i+1]) == 1 for i in xrange(len(bin_n) - 1))


class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
bin_n = bin(n)[2:]
return all(bin_n[i] != bin_n[i+1] for i in xrange(len(bin_n) - 1))


方法二

看别人的代码,速度更快,直接判断是不是在所有交替的字符串之间即可。

class Solution(object):
def hasAlternatingBits(self, n):
"""
:type n: int
:rtype: bool
"""
b = 0b1010101010101010101010101010101010101010101010101010101010101010
while b > 0:
if b == n:
return True
b = b >> 1
return False


Date

2018 年 1 月 17 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: