Created
November 17, 2014 01:43
-
-
Save wangchauyan/f95fa20e3d0a183fd8b6 to your computer and use it in GitHub Desktop.
LeetCode - Plus one
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
time complexity is O(n) and space complexity is O(n) (worse case), best case is O(1)