当前位置:网站首页>leetcode-693.交替位二进制数
leetcode-693.交替位二进制数
2022-08-03 15:53:00 【KGundam】
位运算
题目详情
**给定一个正整数,检查它的二进制表示是否总是 0、1 交替出现:换句话说,就是二进制表示中相邻两位的数字永不相同。
**
示例1:
输入:n = 5
输出:true
解释:5 的二进制表示是:101
示例2:
输入:n = 7
输出:false
解释:7 的二进制表示是:111.
示例3:
输入:n = 11
输出:false
解释:11 的二进制表示是:1011.
第一种方法:正常取余逐位比较
按题目要求老老实实比较每一位和它的前一位
class Solution
{
public:
bool hasAlternatingBits(int n)
{
int pre = -1; //注意初始化
while (n != 0)
{
int cur = n % 2;
if (cur == pre)
return false;
pre = cur;
n /= 2;
}
return true;
}
};
第二种方法:位运算!
举个例子你就懂了,假如有个数字101010101
我们将它右移一位,得到了010101010 ------刚刚好错位了!
相信你已经懂了,再将两者进行异或运算,如果满足交替位二进制数,就会得到111…111全是1的数
然后再根据 n&n-1 == 0的充要条件是n的二进制位上全是1 来验证即可
我的代码:
class Solution
{
public:
bool hasAlternatingBits(int n)
{
long a = n ^ (n >> 1);//注意类型
return (a & (a + 1)) == 0;
}
};
位运算常用技巧
边栏推荐
- 5 v 8.4 v1A charging current charging management IC
- 在 360 度绩效评估中应该问的 20 个问题
- Internship Road: Documenting Confusion in My First Internship Project
- Common distributed theories (CAP, BASE) and consensus protocols (Gosssip, Raft)
- 如何选择合适的损失函数,请看......
- 13、OOM模拟
- DC-DC 2C(40W/30W) JD6606SX2退功率应用
- 使用Make/CMake编译ARM裸机程序(基于HT32F52352 Cortex-M0+)
- ffplay视频播放原理分析
- Introduction to spark learning - 1
猜你喜欢
新一代网状网协议T-Mesh无线通信技术优势介绍
Awesome!Coroutines are finally here!Thread is about to be in the past
How to start an NFT collection
How much do you know about the intelligent operation and maintenance service of data warehouse based on DMS?
Introduction to spark learning - 1
Research on power flow in DC microgrid based on Newton's method (Matlab code implementation)
证实了,百度没有快照了
AI也有健忘症?英国41岁教授专访:解决灾难性遗忘
深入浅出Flask PIN
A new round of competition for speech recognition has started. Will natural dialogue be the next commanding height?
随机推荐
一个文件管理系统的软硬件配置清单
为教育插上数字化的翅膀,网易云信发布「互联网+教育」整体解决方案
AI+BI+可视化,Sugar BI架构深度剖析
爬虫注意
[微信小程序开发者工具] × #initialize
JS基础--判断
Daily practice------There are 10 numbers that are required to be output from large to small by selection method
5 v 8.4 v1A charging current charging management IC
Convex Optimization of Optimal Power Flow (OPF) in Microgrids and DC Grids (Matlab Code Implementation)
JD6606SP5_JD6606SSP_JD6606SASP_JD6621W7百盛新纪元授权代理商
Deep Learning - Install CUDA and CUDNN to implement GPU operation of tensorflow
请问下,flink cdc监控oracle,我看源码是通过sid方式的,请问怎么改成service
神经网络,凉了?
【899. Ordered Queue】
How to use binary search and find whether the rotation in the array contains a (target) value?Rotate the sorted array leetcode 81. Search
MySQL性能优化_小表驱动大表
上亿数据怎么玩深度分页?兼容MySQL + ES + MongoDB
移动应用出海,你的“网络优化”拖后腿了吗?
How to play deep paging with hundreds of millions of data?Compatible with MySQL + ES + MongoDB
美国国防部更“青睐”光量子系统研究路线