LeetCode 693. Binary Number with Alternating Bits
来源:互联网 发布:linux 桌面虚拟化 编辑:程序博客网 时间:2024/05/24 04:17
693. Binary Number with Alternating Bits
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.
代码实现如下:
思路1:
用 t 表示该数字的最后一位,比如10的二进制为1010,则 t = 0;
n /= 2; 如果其二进制最后一位 t 总是等于 n / 2 后剩下的最后一位,说明其二进制相邻位置有相同值,即不交互,返回false;
否则返回true;
class Solution {
public boolean hasAlternatingBits(int n) {
int t = n % 2;
n /= 2;
while(n > 0){
if(t == n % 2) return false;
t = n % 2;
n /= 2;
}
return true;
}
}
思路2:
调用Integer.toBinaryString()方法将十进制数转换位二进制字符串,依次比较当前位是否与下一位相等,相等返回false,否则返回true
class Solution {
public boolean hasAlternatingBits(int n) {
String bits = Integer.toBinaryString(n);
for(int i = 0; i < bits.length() - 1; i++){
if(bits.charAt(i) == bits.charAt(i + 1)) return false;
}
return true;
}
}
阅读全文
0 0
- leetcode 693. Binary Number with Alternating Bits
- leetcode 693. Binary Number with Alternating Bits
- LeetCode-693. Binary Number with Alternating Bits
- LeetCode 693. Binary Number with Alternating Bits
- leetcode 693. Binary Number with Alternating Bits
- Binary Number with Alternating Bits(leetcode)
- 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- 693. Binary Number with Alternating Bits
- Binary Number with Alternating Bits
- leetcode 693. Binary Number with Alternating Bits(附正则表达式)
- LWC 53:693. Binary Number with Alternating Bits
- python--leetcode693. Binary Number with Alternating Bits
- LeetCode 693 Binary Number with Alternating Bits 带有交替位的二进制数
- Binary Number with Alternating Bits问题及解法
- The Joy of Clojure.pdf 英文原版 免费下载
- Hibernate的load()和get()区别
- SpringMVC工作流程
- Spring MVC基本环境搭建
- A星算法详解(个人认为最详细,最通俗易懂的一个版本)
- LeetCode 693. Binary Number with Alternating Bits
- Python in Practice.pdf 英文原版 免费下载
- mysql 高可用性
- 趣图丨哇哦!2018年就要来了!
- Python的各种库函数的管理及一些常用库的安装例如OpenCV和Numpy等
- Kotlin知识笔记(1)
- 记录自己自学编程的历程
- 过了35岁,感觉自己活成了一部《西游记》
- 日记(5)