简体   繁体   中英

Decreasing a binary number by 1 without converting it to an integer

I am modifying the code I used to increase the binary by one. I decided the easiest way was to just subtract the binary from one. I just don't know how to modify it. I mostly works, but when a 0 is subtracting from a 1, I'm not sure what I'm supposed to do with my carry variable. Here's what I have:

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;
}

如果你想要懒惰使用你用来添加一个的相同代码,而是添加两个补码 1。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM