首页 > 其他 > 详细

lintcode 容易题:Flip Bits 将整数A转换为B

时间:2015-10-13 17:01:08      阅读:611      评论:0      收藏:0      [点我收藏+]

题目:

如果要将整数A转换为B,需要改变多少个bit位?

样例

如把31转换为14,需要改变2个bit位。

(31)10=(11111)2

(14)10=(01110)2

挑战

你能想出几种方法?

解题:

A-->B二进制要变化多少位?就是考虑A、B对应的二进制数有多少不同的,A、B的异或结果中出现的1的个数就是需要改变的比特位

问题转换成,10进制的数中,二进制表示情况下1的个数,这个题目之前求过,编程之美上面也有的。

上面的方法1不可取,因为这里的数据有负数。

其他两种方法如下:

Java程序:

利用位运算:

技术分享
class Solution {
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    public static int bitSwapRequired(int a, int b) {
        // write your code here
        int c = a^b;
        int count = 0;
        while(c!=0){
            count += c&1;
            c=c>>>1;
        }
        return count;
    }
};
View Code

总耗时: 2834 ms

利用位运算 与减法

技术分享
class Solution {
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    public static int bitSwapRequired(int a, int b) {
        // write your code here
        int c = a^b;
        int count = 0;
        while(c!=0){
            c = c&(c-1);
            count++;
        }
        return count;
    }
};
View Code

总耗时: 2366 ms

取一位判断一位:

技术分享
class Solution {
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    public static int bitSwapRequired(int a, int b) {
        // write your code here
        int count=0;
        while(a!=0 || b!=0){
            int ai = a&1;
            int bi = b&1;
            if(ai==1 && bi==0 || ai==0 && bi==1)
                count++;
            a = a>>>1;
            b = b>>>1;
        }
        return count;
    }
};
View Code

总耗时: 2103 ms

Python程序:

直接转换成python时间超时。。。

 

lintcode 容易题:Flip Bits 将整数A转换为B

原文:http://www.cnblogs.com/theskulls/p/4874849.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!