zoukankan      html  css  js  c++  java
  • 整数转化 牛客网 程序员面试金典 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
  • 相关阅读:
    switch语句
    switch语句
    if语句三种格式
    dowhile语句
    if语句三种格式
    if语句配对
    ansible
    linux系统中网站服务程序(web服务/httpd服务)
    ansible
    ansible
  • 原文地址:https://www.cnblogs.com/vercont/p/10210321.html
Copyright © 2011-2022 走看看