Plus One

Monisha Mathew
1 min readMar 28, 2019

--

Question: Given a non-empty array of digits representing a non-negative integer, plus one to the integer.

The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.

You may assume the integer does not contain any leading zero, except the number 0 itself.

Example 1:

Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Approach: Let’s keep it simple and get to code!

//Approach 1
//Runtime: 0ms
//Memory usage: 37.4MB
class Solution {
public int[] plusOne(int[] digits) {
int carryOver = 1;
int temp = 0;
for(int i = digits.length-1; i>=0 && carryOver==1; i--){
temp = digits[i] + 1;
digits[i] = temp%10;
carryOver = temp/10;
}
if(carryOver==1){
int[] newDigits = new int[digits.length+1];
newDigits[0] = 1;
for(int i = 0; i<digits.length; i++){
newDigits[i+1] = digits[i];
}
return newDigits;
}
return digits;
}
}

That was quick!!!

Find more posts here.

Cheers & Chao!

--

--