【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 日相关文章推荐
- LeetCode-Shortest Palindrome-解题报告
- leetcode解题报告-342. Power of Four
- 【LeetCode】Number of 1 Bits 解题报告
- LeetCode-Largest Number-解题报告
- leetcode解题报告:238. Product of Array Except Self
- leetcode解题报告:104. Maximum Depth of Binary Tree
- Word Break [Leetcode解题报告]
- LeetCode-Binary Search Tree Iterator-解题报告
- [LeetCode]Spiral Matrix,解题报告
- Leetcode 653. Two Sum IV - Input is a BST 两数相加4 解题报告
- 【LeetCode】655. Print Binary Tree 解题报告(Python)
- LeetCode 解题报告 LRU Cache
- Leetcode 76-MinimumWindowSubstring 解题报告
- Leetcode 120. Triangle 三角形问题(动态规划经典) 解题报告
- [Leetcode] 241. Different Ways to Add Parentheses 解题报告
- [Leetcode] 249. Group Shifted Strings 解题报告
- 解题报告:LeetCode The Skyline Problem(画天际线)
- [Leetcode] 351. Android Unlock Patterns 解题报告
- leetcode解题报告:56. Merge Intervals
- [Leetcode] 525. Contiguous Array 解题报告