整数转换
难度:
标签:
题目描述
Write a function to determine the number of bits you would need to flip to convert integer A to integer B.
Example1:
Input: A = 29 (0b11101), B = 15 (0b01111) Output: 2
Example2:
Input: A = 1,B = 2 Output: 2
Note:
-2147483648 <= A, B <= 2147483647
代码结果
运行时间: 26 ms, 内存: 16.0 MB
/*
* Problem: Determine the number of bits needed to convert integer A to integer B.
* Approach: Use Java Streams to count the number of differing bits.
* XOR A and B, convert to binary string, and count '1's.
*/
import java.util.stream.Stream;
public class BitConversionStream {
public static int countBitsToConvert(int A, int B) {
return (int) Stream.of(Integer.toBinaryString(A ^ B).split(""))
.filter(bit -> bit.equals("1"))
.count(); // Count the number of '1's in the binary string
}
public static void main(String[] args) {
System.out.println(countBitsToConvert(29, 15)); // Output: 2
System.out.println(countBitsToConvert(1, 2)); // Output: 2
}
}
解释
方法:
这个题解利用异或操作来找出两个整数在二进制表示中不同的位。异或操作的特点是相同的位结果为0,不同的位结果为1。因此,将A和B进行异或操作后,不同位上的结果将为1。然后,题解通过遍历这个结果的每一位(总共32位,因为Python中整数是32位),统计值为1的位的数量,这个数量就是A需要改变的位数才能变成B。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
题解中提到需要遍历32位来统计不同的位数,但是对于负数是否需要特别处理或者有不同的计算方式?
▷🦆
你是如何确定使用异或操作来找出两个整数不同的位的,这种方法是否适用于所有整数包括负数?
▷🦆
题解提到了使用32次循环来检查每一位,这是否意味着算法的效率与输入的大小无关?
▷