Skip to content

Instantly share code, notes, and snippets.

@wangchauyan
Created November 17, 2014 01:43
Show Gist options
  • Save wangchauyan/f95fa20e3d0a183fd8b6 to your computer and use it in GitHub Desktop.
Save wangchauyan/f95fa20e3d0a183fd8b6 to your computer and use it in GitHub Desktop.
LeetCode - Plus one
public class Solution {
public int[] plusOne(int[] array) {
if (array == null) return null;
int carry = 0;
for(int i = array.length-1; i >= 0; i--) {
array[i] += (i == array.length-1 ? 1+carry : carry);
carry = array[i]/10;
array[i] %= 10;
}
if(carry == 0) return array;
else {
int[] newArray = new int[array.length+1];
for(int i = 0; i < array.length; i++)
newArray[i+1] = array[i];
newArray[0] = carry;
return newArray;
}
}
}
@wangchauyan
Copy link
Author

time complexity is O(n) and space complexity is O(n) (worse case), best case is O(1)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment