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]
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
Comments
Post a Comment