4

I am trying to add 1 to a byte array containing binary number. It works for some cases and not for others. I cannot convert my array to an integer and add one to it. I am trying to do the addition with the number in the array. If someone could please point me i where I am messing up on this!

Test cases that have worked: 1111, 0, 11

EDIT: I understand how to do it with everyone's help! I was wondering if the binary number had the least significant bit at the first position of the array.

Example: 1101 would be stored as [1,0,1,1]-how could I modify my code to account for that?

 public static byte[] addOne(byte[] A)
     {
       //copy A into new array-size+1 in case of carry 
       byte[] copyA = new byte[A.length+1];
       //array that returns if it is empty 
      byte [] copyB = new byte [1]; 
      //copy A into new array with length+1
      for(byte i =0; i <copyA.length&& i<A.length; i ++)
      {
        copyA[i]=A[i];
      }


    //if there is nothing in array: return 1;
    if(copyA.length == 0)
    {
        //it will return 1 bc 0+1=1
        copyB[0]=1; 

        return copyB;
    }
    //if first slot in array is 1(copyA) when you hit zero you dont have to carry anything. Go until you see zero 
    if(copyA[0] ==1 )
    {
        //loops through the copyA array to check if the position 0 is 1 or 0
        for(byte i =0; i<copyA.length; i ++)
        {
            if(copyA[i] == 0)//if it hits 0 
            {
                copyA[i]=1;//change to one 
                break;//break out of for loop 
            }
            else{
                copyA[i]=0;
            }

        }
        return copyA; 

    }

    else if (copyA[0]==0)
    {
        copyA[0]=1;

    }


    return copyA;

  }
6
  • To copy arrays is better to use System.arraycopy(srcArray, srcPos, destArray, destPos, length) Commented Aug 27, 2015 at 15:18
  • @Emd4600 I believe the OP is trying to simulate integer increment. Commented Aug 27, 2015 at 15:19
  • I know, but at the beginning he copies two arrays. This obviously doesn't solve his problem, but it's might make that portion of the code faster and more readable. Commented Aug 27, 2015 at 15:21
  • Please post one or two examples of before and after to be sure the question is understood. As @PeterLawrey mentions below your logic is too complicated - and I would suggest that for a beginner his solution is also ;) Commented Aug 27, 2015 at 15:23
  • You say that "It works for some cases and not for others". Please share which cases you've tried, which ones work and which ones don't. Commented Aug 27, 2015 at 15:26

3 Answers 3

3

The idea:

100010001 +       1000000 +          1111111 +
        1 =             1 =                1 =
---------         -------            -------
100010010         1000001         (1)0000000

I designed the operation as you can do on paper.

As for decimal operation adding a number is done starting from right (less significant digit) to left (most significant digit).

Note that 0 + 1 = 1 and I finished so I can exit

Instead 1 + 1 = 10 (in binary) so I write 0 (at the rightest position) and I have a remainder of 1 to add to next digit. So I move left of one position and I redo the same operation.

I hope this is helpful to understand it


It is a simple algorithm:

  • Set position to the last byte.
  • If current byte is 0 change it to 1 and exit.
  • If current byte is 1 change it to 0 and move left of one position.

    public static byte[] addOne(byte[] A) {
        int lastPosition = A.length - 1; 
    
        // Looping from right to left
        for (int i = lastPostion; i >= 0; i--) {
            if (A[i] == 0) {
                A[i] = 1; // If current digit is 0 I change it to 1
                return A; // I can exit because I have no reminder
            }
            A[i] = 0;     // If current digit is 1 I change it to 0 
                          // and go to the next position (one position left)
        }
        return A;         // I return the modified array
    }
    

If the starting array is [1,0,1,1,1,1,1,0,0] the resulting array will be [1,0,1,1,1,1,1,0,1].

If the starting array is [1,0,1,1,1,1,1,1,1] the resulting array will be [1,1,0,0,0,0,0,0,0].

If the starting array is [1,1,1,1,1,1,1,1,1] the resulting array will be [0,0,0,0,0,0,0,0,0].

Note If you need to handle this last situation (overflow) in a different manner you can try one of the following:

  • throw an exception
  • enlarge the array of 1 and result [1,0,0,0,0,0,0,0,0,0]

Here is a piece of code to handle both situations:

Throwing exception:

    public static byte[] addOne(byte[] A) throws Exception {
        for (int i = A.length - 1; i >= 0; i--) {
            if (A[i] == 0) {
                A[i] = 1;
                return A;
            }
            A[i] = 0;
            if (i == 0) {
                throw new Exception("Overflow");
            }
        }
        return A;
    }

Enlarging array:

    public static byte[] addOne(byte[] A) {
        for (int i = A.length - 1; i >= 0; i--) {
            if (A[i] == 0) {
                A[i] = 1;
                return A;
            }
            A[i] = 0;
            if (i == 0) {
                A = new byte[A.length + 1];
                Arrays.fill(A, (byte) 0); // Added cast to byte
                A[0] = 1;
            }
        }
        return A;
    }
Sign up to request clarification or add additional context in comments.

11 Comments

I think the OP wants to handle overflow.
If the the answer a bit longer this will result in an array with all zeros.
Yes I would like to be able to handle any carry overs
@DavideLorenzoMARINO thank you for your help! I was wondering if you could step me through your logic (clearly my solution is very complicated ;) and for your Arrays.fill(A,0) this does not work on byte arrays. Any suggestions on any other ways I can fill it?
Thank you so much. So just to make sure I understand this- you started from the last position of the array to check if it was a 0 or 1. The line where you have A[i] = 0 -- why do we need this?
|
2

I suspect it works in some cases but not other as your code is too complicated.

static byte[] increment(byte[] bits) {
    byte[] ret = new byte[bytes.length+1];
    int carry = 1, i = 0;
    for(byte b: bits) {
       // low bit of an add;
       ret[i++] = b ^ carry;
       // high bit of an add.
       carry &= b;
    }
    if (carry == 0)
       return Arrays.copyOf(ret, bytes.length);
    ret[i] = 1;
    return ret;
}

6 Comments

might your solution be a little much for a rank amateur (which I assume the OP probably is)?
@KevinDTimm I try my best. Never try to do someone's homework for them, but if they are interested, they might learn something. ;)
It's clear this is homework, which makes your answer even more challenging for the OP ;) IOW, how does he explain this level of answer to his prof?
@KevinDTimm It's something I ask myself whenever I give an answer to such a question. The code needs to be his/her own, but hopefully the OP may realise it doesn't have to be so complicated and pick up enough ideas.
I appreciate your answer!I was hoping maybe some explanation or suggestions on my current code and what I can do to improve it
|
0

For an array bits containing the binary numbers, the algorithm for adding 1 is:

Boolean carried = true;
for(int i = bits.length-1; i>=0; i--) {
  if(bits[i] == 1 && carried) {
    carried = true;
    bits[i] = 0;
  }
  else if (bits[i] == 0 && carried) {
    carried = false;
    bits[i] = 1;
  }
{

if(carried)
  throw new Exception("Overflow");

4 Comments

In this case- if i wanted to account for any overflow would I add another else if statement?
I've edited the answer (to account overflow). To handle overflow, refer to Davide Lorenzo MARINO's answer
I was wondering- if my array had the binary numbers input backwards meaning the least significant bit is first position of the array like the number 1101 would be stored [1,0,1,1] how would that change the code?
Simply change the for-loop header to: for(int i = 0; i<bits.length; i++) But why do this? I mean storing a binary number 1101 as [1,1,0,1] makes more sense than storing it backwards.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.