Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example 1:
Example 2:
Example 3:
Example 4:
题解:
package com.leetcode;
public class AlternatingBits {
public static void main(String[] args) {
int n = 5;
if (hasAlternatingBits(n))
System.out.println("True");
else
System.out.println("False");
}
public static boolean hasAlternatingBits(int n) {
boolean ans = true;
int curr = n % 2;
n /= 2;
do {
int next = n % 2;
n /= 2;
if (next == curr) {
ans = false;
break;
}
curr = next;
} while (n != 0);
return ans;
}
}