描述
如果要将整数n转换为m,需要改变多少个bit位?
Both n and m are 32-bit integers.
您在真实的面试中是否遇到过这个题? 是
样例
Example 1:
Input: n = 31, m = 14
Output: 2
Explanation:
(11111) -> (01110) there are two different bits.
Example 2:
Input: n = 1, m = 7
Output: 2
Explanation:
(001) -> (111) will change two bits.
挑战
你能想出几种方法?
第一种解法:模拟二进制的运算
public class Solution {
/**
* @param a: An integer
* @param b: An integer
* @return: An integer
*/
public int bitSwapRequired(int a, int b) {
// 记录需要改变的位数
int count = 0;
// 如果a和b相等,则返回0
if(a==b){
return 0;
}
// 创建两个数组,存储a和b的二进制
int[] aList = new int[32];
int[] bList = new int[32];
getBinary(aList,a);
getBinary(bList, b);
// 比较两个数组不一致的位数
for(int i=0;i<32;i++){
if(aList[i]!=bList[i]){
count++;
}
}
return count;
}
/**
* 获取数值的二进制
* 正数的原码,反码,补码是一样的
* 负数的反码等于原码取反,补码等于反码加1
* @param list
* @param n
*/
public void getBinary(int[] list,int n){
int num = Math.abs(n);
// 求原码
int i = 0;
while(num>0){
// 模拟二进制运算
list[i]=num%2;
num /=2;
i++;
}
// 如果是最小的负数-2147483648,没法转换成正数范围0~2147483647 -1~-2147483648
// 最开始的时候没有考虑到界限值
if(n==-2147483648){
list[31] = 1;
}
if(n<0){
// 求反码
for(int j=0;j<list.length;j++){
list[j] = list[j]==0 ? 1: 0;
}
// 求补码
for(int k=1;k<list.length;k++){
// 如果元素的值为0,则直接加1,并终止循环,主要针对第一个元素
if(list[k-1]==0){
list[k-1] = 1;
break;
}else if(list[k-1]==1 || list[k-1]==2){
// 如果元素为1,则将该值变为0,k的元素加1,第一个数时
list[k-1] = 0;
list[k] +=1;
if (list[k]==1){
break;
}
}
}
}
}
public static void main(String[] args){
System.out.println(new Solution().bitSwapRequired(-2147483648, -1));
}
}
第二种解法:利用java提供的一些方法
public class Solution {
/**
* @param a: An integer
* @param b: An integer
* @return: An integer
*/
public int bitSwapRequired(int a, int b) {
// 记录需要改变的位数
int count = 0;
// 如果a和b相等,则返回0
if(a==b){
return 0;
}
StringBuilder astr = new StringBuilder(Integer.toBinaryString(a));
StringBuilder bstr = new StringBuilder(Integer.toBinaryString(b));
// 遍历字符串
if(astr.length()>bstr.length()){
// 刚开始没有考虑到二进制比较应该从低位开始
count = getCount(astr.reverse(),bstr.reverse());
}else{
count = getCount(bstr.reverse(),astr.reverse());
}
return count;
}
public int getCount(StringBuilder maxStr,StringBuilder minStr){
int count = 0;
// 以位数小的字符串为循环对象,进行比较
for(int i=0;i<minStr.length();i++){
if(maxStr.charAt(i)!=minStr.charAt(i)){
count++;
}
}
// 比较位数大的字符串的剩余字符,只要等于1.count++
for(int i=minStr.length();i<maxStr.length();i++){
if(maxStr.charAt(i)=='1'){
count++;
}
}
return count;
}
public static void main(String[] args){
System.out.println(new Solution().bitSwapRequired(14, 31));
}
}