程序员面试金典-5.4整数转化

一、问题描述

编写一个函数,确定需要改变几个位,才能将整数A转变成整数B。给定两个整数int A,int B。请返回需要改变的数位个数。

测试样例:

10,5
返回:4
二、思路描述
首先对A和B取异或运算,然后计算该数字中的1的个数,本人采用的思路是先判断这个数字是不是负数,然后诸位的判断是不是1。有种更简单的方法是 使用n=n&(n-1)的方法,效率更高

三、代码
import java.util.*;

public class Transform {
    public int calcCost(int A, int B) {
        // write code here
        int a=A^B;
        int temp=1;
        int numcount=0;
        boolean flag=false;//如果a是负数;       
	 if(a<0){
            a=-a;
            flag=true;
        }
        while(temp<=a && temp>0){//如果通过将a不断左移来判断a中1的个数,不需要管a是正数还是负数
            if((temp&a)!=0){
                numcount++;
            }
            temp=temp<<1;
        }
        if(flag)
            numcount++;
        return numcount;
    }
}
第二种方式:
import java.util.*;

public class Transform {
    public int calcCost(int A, int B) {
        // write code here
        int a=A^B;
        int count=0;
        while(a!=0){
            a&=(a-1);
            count++;
        }
        return count;
        /*
        int a=A^B;
        int temp=1;
        int numcount=0;
        boolean flag=false;//如果a是负数
        if(a<0){
            a=-a;
            flag=true;
        }
        while(temp<=a && temp>0){
            if((temp&a)!=0){
                numcount++;
            }
            temp=temp<<1;
        }
        if(flag)
            numcount++;
        return numcount;
        */
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值