Bits


Description

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

Example

Input: n = 5
Output: true
Explanation: The binary representation of 5 is: 101

Solution

/**
 * @param {number} n
 * @return {boolean}
 */
var hasAlternatingBits = function(n) {
    let pre = -1;
    while(n) {
        if(pre === n % 2) return false;
        pre = n % 2;
        n = parseInt(n /2);
    }
    return true;
};

Result

Accepted
204/204 cases passed (49 ms)
Your runtime beats 99.37 % of javascript submissions
Your memory usage beats 9.46 % of javascript submissions (42.5 MB)


文章作者: 阿汪同学
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 阿汪同学 !
评论
  目录