我使用以下代码进行二进制求和:
class dump{
public static void main(String[] args){
final int number0 = Integer.parseInt("000", 2);
final int number1 = Integer.parseInt("1", 2);
final int sum = number0 + number1;
System.out.println(Integer.toBinaryString(sum));
}
}
问题是我没有得到答案的精确精度 - 例如 000 + 1 或 00 + 1 都解析为 1。
由于我打算使用结果作为 hashmap 中的键,因此结果的非唯一性是一个问题。
如何获得 00+1=>01 或 000+1 =>001。
最佳答案
The problem is that I do not get the exact precision of the answer
无关紧要的前导零对答案的精度没有影响:答案 1
与 001
或 00000000000001
完全相同 - 它是相同的数字。
Since I intend to use the result as the key in a hashmap ,the non-uniqueness of the result is a problem.
如果您要使用这样的字符串作为排序映射中的键,则会出现问题,因为键有时会出现乱序。在 HashMap 中,这不是问题,因为 Integer.toBinaryString(sum)
会删除所有数字中的前导零,因此您永远不会看到像 000
这样的数字你的程序。如果这些数字确实来自外部,您可以在将它们用作哈希键之前通过解析并转换为二进制来标准化它们。
关于java - 精确的二进制求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18403592/