Last active
December 16, 2015 18:49
-
-
Save daifu/5480481 to your computer and use it in GitHub Desktop.
Plus One
This file contains hidden or 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
/* | |
Given a number represented as an array of digits, plus one to the number. | |
*/ | |
public class Solution { | |
public int[] plusOne(int[] digits) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
int len = digits.length - 1; | |
digits[len] = digits[len] + 1; | |
int carry = digits[len] >= 10 ? 1 : 0; | |
// check if the last digit + 1 > 10 | |
while(carry > 0 && len > 0) { | |
// get the single digit for the position len | |
digits[len] = digits[len] - 10; | |
len--; | |
// add the carry to higher digit | |
digits[len] += carry; | |
carry = digits[len] >= 10 ? 1 : 0; | |
} | |
// check and make sure the each digit is < 10 | |
if(digits[len] >= 10) digits[len] -= 10; | |
int[] ret = new int[digits.length+carry]; | |
ret[len] = carry; | |
int fLen = digits.length+carry-1; | |
for(int i = digits.length-1; i>=0; i--) { | |
// copy over the digits to the ret | |
ret[fLen] = digits[i]; | |
fLen--; | |
} | |
return ret; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment