OJ Lintcode 将整数A转换为B

如果要将整数A转换为B,需要改变多少个bit位?
您在真实的面试中是否遇到过这个题?
Yes
样例
如把31转换为14,需要改变2个bit位。
(31)10=(11111)2
(14)10=(01110)2

class Solution {
public:
    /**
     *@param a, b: Two integer
     *return: An integer
     */
    deque<int>  trantobinary(int a){
        deque<int> vi;
        while(a!=0){
            int rem=a%2;
            int res=a/2;

            vi.push_back(rem);
            a=res;
        }
        return vi;
    }

    deque<long long> tobinary(long long num){
        deque<long long> d;
        if(num<0){
             num=4294967296+num;
        }

        while(num!=0){
            //余数
            int rem=num%2;
            //商
            int res=num/2;
            num=res;
            d.push_back(rem);
        }
        return d;
    }

    int bitSwapRequired(int a, int b) {
        // write your code here
        int counts=0;
        deque<long long> va=tobinary(a);
        deque<long long> vb=tobinary(b);

        int diff=va.size()-vb.size();
        diff=abs(diff);
        if((va.size())<(vb.size())){
            for(int i=0;i<diff;i++){
                va.push_back(0);
            }
        }
        else{
            for(int i=0;i<diff;i++){
                vb.push_back(0);
            }
        }
    //  cout<<counts<<endl;
    //  counts=0;
        for(int i=0;i<va.size();i++){
            if(va[i]!=vb[i]){

            //  cout<<"i :"<<i<<" va :"<<va[i]<<" vb :"<<vb[i]<<" counts: "<<counts<<" "<<endl;
                counts++;
            }
        }   
        return counts;
    }
};

    原文作者:zhaozhengcoder
    原文地址: https://www.jianshu.com/p/cd5afe4a05aa#comments
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞