资讯专栏INFORMATION COLUMN

[LintCode] Flip Bits

joyvw / 885人阅读

摘要:的二进制补码就是个,因此这道题一定要考虑正负号的问题。然后去检查的二进制包含多少个,方法是对的每一位除以取余。如果为,就说明那一位为,即和在那一位不同,需要进行转换。每次取余之后,减小为二分之一,删除已经检查过的高位。

Problem

Determine the number of bits required to flip if you want to convert integer n to integer m.

Example

Given n = 31 (11111), m = 14 (01110), return 2.

Note

-1的二进制补码就是32个1,因此这道题一定要考虑正负号的问题。
先将a和b异或得到c,若c为负,就说明a和b的符号不同,所以要多一次符号位的转换。
然后去检查c的二进制包含多少个1,方法是对c的每一位除以2取余。如果为1,就说明那一位为1,即a和b在那一位不同,需要进行转换。每次取余之后,c减小为二分之一,删除已经检查过的高位。

Solution
class Solution {
    public static int bitSwapRequired(int a, int b) {
        int c = a ^ b, count = 0;
        if (c < 0) {
            c ^= Integer.MIN_VALUE;
            count++;
        }
        while (c != 0) {
            count += c % 2;
            c /= 2;
        }
        return count;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/65675.html

相关文章

  • [LintCode/CC] Update Bits [Merge Bits]

    Problem Given two 32-bit numbers, N and M, and two bit positions, i and j. Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at...

    KnewOne 评论0 收藏0
  • [LintCode] Swap Bits

    Problem Write a program to swap odd and even bits in an integer with as few instructions as possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on). Example 5 = (101)2 => ...

    ls0609 评论0 收藏0
  • [LintCode] UTF-8 Validation

    Problem A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules: For 1-byte character, the first bit is a 0, followed by its unicode code.For n-bytes character, the first n...

    tolerious 评论0 收藏0
  • [LintCode] Count 1 in Binary [典型位运算题目]

    摘要:这道题,给我解决了两个疑问,还剩一个。首先是要用无符号右移运算符,其次是可以用一个不断左移的二进制作为参照。 Problem Count how many 1 in binary representation of a 32-bit integer. Example Given 32, return 1 Given 5, return 2 Given 1023, return 9 Ch...

    ZHAO_ 评论0 收藏0
  • [LintCode] Gray Code

    摘要:参考了的算法,简化了一下每个循环更新对应最高位是第位,就增加个数为倒序循环次,会镜像提取上一次循环产生的结果镜像镜像镜像 Problem The gray code is a binary numeral system where two successive values differ in only one bit. Given a non-negative integer n r...

    cocopeak 评论0 收藏0

发表评论

0条评论

joyvw

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<