Created
May 25, 2015 16:19
-
-
Save ianpark/a2f13b8156cb5a5d9f2e to your computer and use it in GitHub Desktop.
LeetCode / plusOne
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
vector<int> plusOne(vector<int>& digits) { | |
if (digits.empty()) return digits; | |
bool overflow = true; | |
for (int i = 0; i < digits.size(); ++i) { | |
if (digits[i] != 9) { | |
overflow = false; | |
break; | |
} | |
} | |
int carry = 1; | |
int newSize = digits.size() + (overflow ? 1 : 0); | |
vector<int> result(newSize, 0); | |
int org = digits.size() - 1; | |
int dst = result.size() - 1; | |
while (org >= 0 && dst >= 0) { | |
if (digits[org] == 9 && carry) { | |
result[dst] = 0; | |
} | |
else { | |
result[dst] = digits[org] + carry; | |
carry = 0; | |
} | |
org--; | |
dst--; | |
} | |
if (carry > 0) result[0] = carry; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment