整数转化 牛客网 程序员面试金典 C++ Python

整数转化 牛客网 程序员面试金典 C++ Python

  • 题目描述

  • 编写一个函数,确定需要改变几个位,才能将整数A转变成整数B。

  • 给定两个整数int A,int B。请返回需要改变的数位个数。

  • 测试样例:

  • 10,5

  • 返回:4

C++

class Transform {
public:
    //run:3ms memory:480k
    int calcCost(int A, int B) {
        int C = A^B;
        return getOneCount(C);
    }
    
    int getOneCount(int x){
        int count = 0;
        for(;x;count++) x = x & (x-1);
        return count;
    }
};

Python

class Transform:
    #run:32ms memory:5728k
    def calcCost(self, A, B):
        C = A^B
        return self.getOneCount(C)
    
    def getOneCount(self,x):
        count =0
        while x:
            count += 1
            x = x & (x -1)
        return count

 

posted @ 2018-09-18 12:50  vercont  阅读(120)  评论(0编辑  收藏  举报