当前位置:网站首页>693. Binary Number with Alternating Bits
693. Binary Number with Alternating Bits
2022-06-22 12:26:00 【Sterben_Da】
693. Binary Number with Alternating Bits
Easy
945103Add to ListShare
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Input: n = 5 Output: true Explanation: The binary representation of 5 is: 101
Example 2:
Input: n = 7 Output: false Explanation: The binary representation of 7 is: 111.
Example 3:
Input: n = 11 Output: false Explanation: The binary representation of 11 is: 1011.
Constraints:
1 <= n <= 231 - 1
class Solution:
def hasAlternatingBits(self, n: int) -> bool:
"""
assert Solution().hasAlternatingBits(5)
相邻2个二进制位不同
解题思路:简单的判断当前最后末尾位与之前的末位是否相同,相同的返回False,
不相同向右移一位接着重复,直到为0
时间复杂度:O(logn)
参考别人的解题思路:
n = 1 0 1 0 1 0 1 0
n >> 1 0 1 0 1 0 1 0 1
这里不能直接 n & (n >> 1) assert not Solution().hasAlternatingBits(4)
n ^ n>>1 1 1 1 1 1 1 1 1
n 1 1 1 1 1 1 1 1
n + 1 1 0 0 0 0 0 0 0 0
n & (n+1) 0 0 0 0 0 0 0 0
时间复杂度:O(1)
"""
# last = n & 1
# n >>= 1
# while n != 0:
# if last == (n & 1):
# return False
# last = n & 1
# n >>= 1
# return True
n = n ^ n >> 1
return n & (n + 1) == 0边栏推荐
猜你喜欢

SiCf batch activation service node

In C # development, the third-party components lambdaparser, dynamicexpresso and z.expressions are used to dynamically parse / evaluate string expressions

SAP-ABAP- 如何查找表,字段有哪些关联表

SAP-FI-财务报表版本设定

建立自己的网站(5)

重磅直播|BizDevOps:数字化转型浪潮下的技术破局之路

Tianyi cloud digital government smart data center has passed the certification

Help financial informatization innovation, Jushan database has won more than 50 financial customers recently

SequoiaDB分布式数据库2022.5月刊

智龄语音+php
随机推荐
胡润研究院首发中国元宇宙潜力企业榜,巨杉数据库入选未来之星企业
Sap-abap- how to transfer material master data, supplier master data, work orders, purchase orders and other information to external systems in real time - implicit enhancement.
老王说系列第六期:PHP程序员要建立自己的自信心
微信公众号开发注意事项
MySQL_ Addition, deletion and modification of data processing
2022-6-21OS复习成组链接法
termux设置电脑连接手机。(敲打命令贼快),手机termux端口8022
[QT] QT get standard system path
leetcode LCP 10. 二叉树任务调度
Sap-abap- how to call an external interface by webapi
Sap-abap-se14 how to recover lost data
SAP-ABAP- 如何查找表,字段有哪些关联表
Fast establishment of tensorflow2 model optimization environment
Repair flutter_ webview_ The problem of web layer residue when the plugin slides out of the page
leetcode 32. 最长有效括号
access_ How to deal with token failure after less than two hours
Reconstruction practice of complex C-end project of acquisition technology
Windows system installs multiple MySQL versions (without uninstalling the original version), and the old and new versions are compatible.
【Qt】QFileInfo获取文件名的各个组成部分
MySQL笔记