3

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Example:

Given [1,2,3] which represents 123, return [1,2,4].

Given [9,9,9] which represents 999, return [1,0,0,0].

My code is not working for the input [9,8,7,6,5,4,3,2,1,0] the output comes as just [9]

Can anyone tell me why?

public class Solution {
    /**
    * @param digits a number represented as an array of digits
    * @return the result
    */
    public int[] plusOne(int[] digits) {
        // Write your code here
        float n = 0;
        for(int i = 0; i < digits.length; i++) {
            n = n*10 + digits[i];
        }
        n++;
        String s = Float.toString(n);
        s = s.substring(0, s.indexOf("."));
        int l = s.length();
        int result[] = new int[l];
        for(int i = 0; i < l; i++) {
            result[i] = Integer.parseInt(Character.toString(s.charAt(i)));
        }
        return result;
    }
}
16
  • Why are you using a float to store an integer number? Commented Nov 23, 2015 at 16:49
  • This is look like school exercise. You teacher expect that you will work with array directly Commented Nov 23, 2015 at 16:50
  • @TimB because the number can be greater than the max integer value Commented Nov 23, 2015 at 16:51
  • 1
    Are you sure you aren't supposed to do this by operating on the incoming array? i.e. just start at the end, add 1. If it overflows set to 0 and add 1 to next, etc. Commented Nov 23, 2015 at 16:51
  • @talex this is coding exercise on lintcode Commented Nov 23, 2015 at 16:52

5 Answers 5

3

For the input [9,8,7,6,5,4,3,2,1,0], the value of n after this code:

float n = 0;
for(int i = 0; i < digits.length; i++) {
    n = n*10 + digits[i];
}
n++;

... is 9.8765435E9. Then, you go on and take the substring of this until the decimal point, which is 9, so the result becomes 9.

It would work better if you changed the type of n from float to long, and converted to string using Long.toString.

But this whole approach of creating n, adding 1, and then converting to String, and then converting to an array is awkward, error prone, and cannot work with larger arrays, as it becomes subject to integer overflow, unless you change the type of n to BigInteger. This solution would not pass in any tests or programming interviews.

Consider this alternative that is simpler, and will work with arbitrarily many digits (as permitted by array size) without worrying about integer overflow:

public int[] plusOne(int[] digits) {
    for (int i = digits.length - 1; i >= 0; --i) {
        digits[i]++;
        if (digits[i] < 10) {
            return digits;
        }
        digits[i] = 0;
    }
    int[] result = new int[digits.length + 1];
    System.arraycopy(digits, 0, result, 1, digits.length);
    result[0] = 1;
    return result;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer is the best among all of them because you provided the reason why my code was failing. Thanks for the alternative code too
1

If you want to go your strange way you need to use BigInt instead of float

But normally this problem is solved by increment last digit and go to nex one in case of overflow.

Like that:

  1. consider last digit
  2. increment current digit
  3. if it is 10 make change it to 0, move one digit left and go to 2. Check special case that no digit is left. In this case prepend 0 to your array
  4. you have required result.

Comments

1

Something like this is almost certainly what they have in mind:

int result = new int[digits.length+1]; // Result with room for 1 more digit
boolean carry = true; // Are we adding 1
for (int i=digits.length-1;i>0;i++) { // Loop from end of digits
   if (carry) {
       if (digits[i]==9) { // 9 goes to 0 and carries forwards
          result[i+1]=0;
       } else {
          result[i+1]=digits[i]+1; // Other values get incremented and carry goes
          carry=false;
       }
   } else {
      result[i+1]=digits[i];
   }
}

// If we still have a carry set the new first digit (otherwise it's already at 0.
if (carry) {
  result[0]=1;
}

6 Comments

This code always add digit. even if this isn't necessary
Where? It only adds if carry is true.
I mean resulting array always longer then input
Yes it will have an extra 0 at the start. That can be avoided if needed but I'll leave that for sadiq to do if it is a requirement since I already basically wrote his exercise for him. (Note that the value is correct even with a leading zero)
Now i will complain about spoon-feeding which is not appreciated on this site. There are people who always complain. It's me :)
|
0
public int[] plusOne(int[] digits) {

    int n = digits.length;

    for(int i=n-1;i>=0;i--){
        if(digits[i]!=9){
            digits[i]+=1;
            return digits;
        }
        digits[i]=0;

    }
    int [] newDigits = new int [n+1];
    newDigits[0]=1;
    return newDigits;
}

2 Comments

Hi - generally code only answers aren't helpful. Can you explain why this code works, and how it is better/different to other solutions?
Lets start from the last digit Case I. 1. if the last digit is not equal to 9 eg: 144 then we will take last digit and add 1 to it and return returned : 145 2. If the last digit is equal to 9 eg : 129 then we will make that 9 to 0 and loop through to digit left to it returned : 130 3. if all the digits are 9 eg :999 then lets make all 9 to 0 and create a new array with digits.lenth+1 where all default elements are 0. and put 1 to first element it will be 1000 lets me know if it is not clear
0
public ArrayList<Integer> plusOne(ArrayList<Integer> A) {
       // ArrayList<Integer> abc= new ArrayList<>();
        if(A.get(0)==0){
            A.remove(0);
        }

        if(A.get(A.size()-1)<9){
            A.add(A.size()-1, A.get(A.size()-1)+1);
            A.remove(A.size()-1);
            return A;
        }
        int end= A.size()-1;
       while(A.get(end)== 9){
           A.add(end,0);
           A.remove(end+1);
          end=end-1;
           if(A.get(end)<9) {
               A.add(end, A.get(end) + 1);
               A.remove(end +1);
           }
       }
        return A;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.