Monday, June 5, 2017

Plus one

Problem Statement

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.

Link to GitHub :Code

input = {1, 4, 9, 9}
output ={1, 5, 0, 0 }


  • We need to traverse from the end .
  • If digit is less than 9 than increment by one and return the array
  • If the digit is 9 then replace it with 0
  • The last part of the code is needed if all the digits in the array are 9 ex 9999

public static int [] get(int [] digits)
 //Loop through the array
 for(int i=digits.length-1;i>=0;i--)
  //check if the digits are less than 9
   return digits;
  //If the no is greater than 1 then assign 0
 //This last part of code is only for the case that the whole input array is 9s.
 //For example : 99999-----> 100000
 int [] newNumber = new int [digits.length+1];
 return newNumber;


Sample Output

No comments:

Post a Comment