2019独角兽企业重金招聘Python工程师标准>>>
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.
解决:
① 判断一个数的二进制表示中,相邻的位是否为不同的值,即01交替。
class Solution { //17ms
public boolean hasAlternatingBits(int n) {
String tmp = Integer.toBinaryString(n);
for (int i = 0; i < tmp.length() - 1;i ++){
if (tmp.charAt(i) == tmp.charAt(i + 1)) return false;
}
return true;
}
}
② 位操作解决。
class Solution { //15ms
public boolean hasAlternatingBits(int n) {
while (n != 0){
int a = n & 1;
n >>= 1;
int b = n & 1;
if (a == b) return false;
}
return true;
}
}
③
class Solution { //19ms
public boolean hasAlternatingBits(int n) {
if(n <= 0) {
return false;
}
if(n == 1) {
return true;
}
int tmp = n % 2;
n = n / 2;
while(n != 0) {
if(n % 2 == tmp) {
return false;
}
tmp = n % 2;
n /= 2;
}
return true;
}
}