Add One To Number - The Coding Shala

Home >> Interview Questions >> Add One to Number

Add One To Number InterviewBit Solution

Given a non-negative number represented as an array of digits, add 1 to the number ( increment the number represented by the digits ).
The digits are stored such that the most significant digit is at the head of the list.
Example:
If the vector has [1, 2, 3] the returned vector should be [1, 2, 4]
as 123 + 1 = 124.
Add One to Number Java Program - The Coding Shala

Solution:

Here first we need to remove leading zeros from the given vector then add 1 to vector.

Java Code::

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
    public ArrayList<Integer> plusOne(ArrayList<Integer> A) {
        int i=0;
        while(i<= A.size()-1 && A.get(i)==0) A.remove(i);
       // for(int i=0;i<A.size();i++) System.out.print(A.get(i)+" ");
        int carry = 1;
        for(i=A.size()-1;i>=0;i--){
            int tmp = A.get(i)+carry;
            if(tmp>9){
                A.set(i,tmp%10);
                carry = 1;
            }else{
                A.set(i,tmp);
                carry = 0;
                break;
            }
        }
        if(carry > 0) A.add(0,carry);
        return A;
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

New Year Chaos Solution - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Method Overloading - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala