Description
Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.
Example
Example 1:
Input: 5Output: TrueExplanation:The binary representation of 5 is: 101
Example 2:
Input: 7Output: FalseExplanation:The binary representation of 7 is: 111.
Example 3:
Input: 11Output: FalseExplanation:The binary representation of 11 is: 1011.
Example 4:
Input: 10Output: TrueExplanation:The binary representation of 10 is: 1010.
public class Solution { /** * @param n: a postive Integer * @return: if two adjacent bits will always have different values */ public boolean hasAlternatingBits(int n) { // Write your code here //通过位运算,判断到最高位(最高为肯定为1) while(n != 0) { //取出尾数 int temp = n % 2; //将n移位,取出尾数 n= n >> 1; //取出移位之后的尾数 int test = n % 2; // 用过异或判断是否不同(不同便是1) if((temp ^ test) != 1) { return false; } } return true; }}