987. Binary Number with Alternating Bits

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: 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.
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;
    }
}
posted @ 2019-04-02 21:46  故人叹  阅读(98)  评论(0)    收藏  举报