[LeetCode] Binary Number with Alternating Bits 有交替位的二进制数

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

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.

这道题让我们判断一个二进制数的1和0是否是交替出现的,博主开始也美想到啥简便方法,就一位一位来检测呗,用个变量bit来记录上一个位置的值,初始化为-1,然后我们用‘与’1的方法来获取最低位的值,如果是1,那么当此时bit已经是1的话,说明两个1相邻了,返回false,否则bit赋值为1。同理,如果是0,那么当此时bit已经是0的话,说明两个0相邻了,返回false,否则bit赋值为0。判断完别忘了将n向右移动一位。如果while循环退出了,返回true,参见代码如下:

解法一:

class Solution {

public:
    bool hasAlternatingBits(int n) {
        int bit = -1;
        while (n > 0) {
            if (n & 1 == 1) {
                if (bit == 1) return false;
                bit = 1;
            } else {
                if (bit == 0) return false;
                bit = 0;
            }
            n >>= 1;
        }
        return true;
    }
}; 

下面这种解法写的更加简洁了,我们不需要用if条件来判断,而是可以通过‘亦或’1的方式来将0和1互换,当然我们也可以通过d = 1 - d 来达到同样的效果,但还是写成‘亦或’1比较叼,while循环的条件是最低位等于d,而d不停的在0和1之间切换,n每次也向右平移一位,这样能交替检测0和1,循环退出后,如果n为0,则返回true,反之则返回false,参见代码如下:

解法二:

class Solution {

public:
    bool hasAlternatingBits(int n) {
        int d = n & 1;
        while ((n & 1) == d) {
            d ^= 1;
            n >>= 1;
        }
        return n == 0;
    }
}; 

下面这种解法就十分的巧妙了,利用了0和1的交替的特性,进行错位相加,从而组成全1的二进制数,然后再用一个检测全1的二进制数的trick,就是‘与’上加1后的数,因为全1的二进制数加1,就会进一位,并且除了最高位,其余位都是0,跟原数相‘与’就会得0,所以我们可以这样判断。比如n是10101,那么n>>1就是1010,二者相加就是11111,再加1就是100000,二者相‘与’就是0,参见代码如下:

解法三:

class Solution {
public:
    bool hasAlternatingBits(int n) {
        return ((n + (n >> 1) + 1) & (n + (n >> 1))) == 0;
    }
};

下面这种解法也很巧妙,先将n右移两位,再和原来的n亦或,得到的新n其实就是除了最高位,其余都是0的数,然后再和自身减1的数相‘与’,如果是0就返回true,反之false。比如n是10101,那么n/4是101,二者相‘亦或’,得到10000,此时再减1,为1111,二者相‘与’得0,参见代码如下:

解法四:

class Solution {
public:
    bool hasAlternatingBits(int n) {
        return ((n ^= n / 4) & (n - 1)) == 0;
    }
};

参考资料:

https://discuss.leetcode.com/topic/106280/c-concise-code

https://discuss.leetcode.com/topic/106356/oneliners-c-java-ruby-python 

https://discuss.leetcode.com/topic/106295/java-c-very-simple-solution-1-line

本文转自博客园Grandyang的博客,原文链接:[LeetCode] Binary Number with Alternating Bits 有交替位的二进制数

,如需转载请自行联系原博主。

时间: 2024-10-25 06:37:30

[LeetCode] Binary Number with Alternating Bits 有交替位的二进制数的相关文章

[LeetCode]191.Number of 1 Bits

题目 Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should r

[LeetCode] Number of 1 Bits & Reverse Integer - 整数问题系列

目录:1.Number of 1 Bits  - 计算二进制1的个数 [与运算] 2.Contains Duplicate - 是否存在重复数字 [遍历]3.Reverse Integer - 翻转整数 [int边界问题]4.Excel Sheet Column Number - Excel字符串转整数 [简单]5.Power of Two & Happy Number - 计算各个位数字 [%10 /10] 一.Number of 1 Bits  题目概述:Write a function t

【LeetCode从零单排】No 191.Number of 1 Bits(考察位运算)

题目 Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should r

[LeetCode] Number of 1 Bits

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). For example, the 32-bit integer '11' has binary representation 00000000000000000000000000001011, so the function should retu

[LeetCode] Binary Tree Level Order Traversal 二叉树层次遍历(DFS | BFS)

目录:1.Binary Tree Level Order Traversal - 二叉树层次遍历 BFS 2.Binary Tree Level Order Traversal II - 二叉树层次遍历从低往高输出 BFS 3.Maximum Depth of Binary Tree - 求二叉树的深度 DFS4.Balanced Binary Tree - 判断平衡二叉树 DFS5.Path Sum - 二叉树路径求和判断DFS 题目概述:Given a binary tree, return

[LeetCode]200.Number of Islands

题目 Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded

[LeetCode] Binary Tree Paths - 二叉树基础系列题目

目录:1.Binary Tree Paths - 求二叉树路径 2.Same Tree - 判断二叉树相等 3.Symmetric Tree - 判断二叉树对称镜像 Binary Tree Paths 题目概述:Given a binary tree, return all root-to-leaf paths. For example, given the following binary tree: 1 / \ 2 3 \ 5 All root-to-leaf paths are: ["1-

[LeetCode] Ugly Number II

Write a program to find the n-th ugly number. Ugly numbers are positive numbers whose prime factors only include 2, 3, 5. For example, 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers. Note that 1 is typically treated as an

[LeetCode] Palindrome Number & Valid Palindrome - 回文系列问题

题目概述: Determine whether an integer is a palindrome. Do this without extra space. 题目分析: 判断数字是否是回文 例如121.656.3443 方法有很多,正着看和到着看两数相同:当然负数显然不是回文 我的方法: 第一种方法: 由于没有没有看到前面的without extra space.采用的方法是把数字转换为字符串,依次比较最前和最后两个字符是否相同,直到遍历完毕. /** * 判断一个数字是否是回文数字 Pal