Add One To Number
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.
NOTE: Certain things are intentionally left unclear in this question which you should practice asking the interviewer. For example, for this problem, following are some good questions to ask :
Q : Can the input have 0’s before the most significant digit. Or in other words, is
0 1 2 3a valid input?A : For the purpose of this question, YES
Q : Can the output have 0’s before the most significant digit? Or in other words, is
0 1 2 4a valid output?A : For the purpose of this question, NO. Even if the input has zeroes before the most significant digit.
public class Solution {
    public ArrayList<Integer> plusOne(ArrayList<Integer> A) {
        ArrayList<Integer> t=new ArrayList<>();
        int carry=1;
        for(int j=A.size()-1;j>=0;j--){
            int num=A.get(j)+carry;
            carry=num/10;
            num=num%10;
            t.add(0,num);
        }
        if(carry==1){
            t.add(0,1);
        }
        ArrayList<Integer> ans=new ArrayList<>();
        boolean flag=true;
        for(int i=0;i<t.size();i++){
            if(flag && t.get(i)==0){
                
            }
            else{
                flag=false;
                ans.add(t.get(i));
            }
        }
        return ans;
    }
}
Last updated