Skip to content

Instantly share code, notes, and snippets.

@daifu
Last active December 16, 2015 18:49
Show Gist options
  • Save daifu/5480481 to your computer and use it in GitHub Desktop.
Save daifu/5480481 to your computer and use it in GitHub Desktop.
Plus One
/*
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