gpt4 book ai didi

java - 将二进制数减 1 而不将其转换为整数

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:20 25 4
gpt4 key购买 nike

我正在修改用于将二进制数加一的代码。我决定最简单的方法就是用一减去二进制。我只是不知道如何修改它。我主要工作,但是当 0 从 1 中减去时,我不确定我应该如何处理我的进位变量。这是我所拥有的:

String decB(String b)
{
String b2 = "0001"; //binary of 1 will be subtracted from the user input binary
String b3 = ""; //result initialized as empty string
int i1 = b.length()-1; //start at the end of the first string
int i2 = b2.length()-1; //start at the end of the second string
int c = 0; //initialize storage as zero. Prevents negative digits.

while (i1 >= 0 && i2 >= 0) //while digits are either one or zero
{
int difference = ((b.charAt(i1)-'0')-(b2.charAt(i2)-'0')+c); //subtracts the binaries
c = difference/2;
b3 = difference%2 + b3;
i1--;
i2--;
}
if (c < 0)
b3 = b3 + c;

return b3;
}

最佳答案

如果您想偷懒,请使用与添加代码相同的代码,但添加 two's complement共 1 个。

关于java - 将二进制数减 1 而不将其转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36490697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com