判斷一個數的二進制表示是否爲01交替

Binary Number with Alternating Bits

問題:spa

Given a positive integer, check whether it has alternating bits: namely, if two adjacent bits will always have different values.it

Example 1:io

Input: 5
Output: True
Explanation:
The binary representation of 5 is: 101

Example 2:class

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:di

Input: 10
Output: True
Explanation:
The binary representation of 10 is: 1010.

解決:while

① 判斷一個數的二進制表示中,相鄰的位是否爲不一樣的值,即01交替。return

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;     } }

相關文章
相關標籤/搜索