Created
August 30, 2020 14:02
-
-
Save AbhiAgarwal192/8c3bed0eb89ce2c6f500b68b8014a5af to your computer and use it in GitHub Desktop.
Given a non-empty array of digits representing a non-negative integer, increment one to the integer.
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
public class Solution { | |
public int[] PlusOne(int[] digits) { | |
int len = digits.Length; | |
if(len == 0){ | |
return digits; | |
} | |
int i=len-1; | |
int carry = 1; | |
while(i>=0){ | |
if(digits[i]+carry>9){ | |
int pcarry = (digits[i]+carry)/10; | |
digits[i] = (digits[i]+carry)%10; | |
carry = pcarry; | |
} | |
else{ | |
digits[i] = digits[i]+carry; | |
carry = 0; | |
} | |
if(carry == 0){ | |
break; | |
} | |
i--; | |
} | |
if(carry>0){ | |
int[] tDigits = new int[len+1]; | |
tDigits[0] = carry; | |
for(i=0;i<len;i++){ | |
tDigits[i+1] = digits[i]; | |
} | |
digits = tDigits; | |
} | |
return digits; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment