Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
<Solution>這題不困難,就是把數值加1
處理好進位問題就可以了
code 如下
c++
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
class Solution { | |
public: | |
vector<int> plusOne(vector<int>& digits) { | |
if(digits.size() == 0) { | |
return digits; | |
} | |
else if(digits.back() < 9) { | |
digits.back() += 1; | |
return digits; | |
} | |
digits.back() += 1; | |
int carry = digits.back() / 10; | |
digits.back() %= 10; | |
for(int i = digits.size() - 2; i >= 0; i--) { | |
digits[i] += carry; | |
carry = digits[i] / 10; | |
digits[i] %= 10; | |
} | |
if(carry) { | |
digits.insert(digits.begin(), carry); | |
} | |
return digits; | |
} | |
}; |
kotlin
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
class Solution { | |
fun plusOne(digits: IntArray): IntArray { | |
val ans = digits.toMutableList() | |
var sum = 0 | |
var carry = 0 | |
for(i in ans.lastIndex downTo 0) { | |
sum = if (i == ans.lastIndex) { | |
ans[i] + 1 + carry | |
} else { | |
ans[i] + carry | |
} | |
if(sum > 9) { | |
ans[i] = sum % 10 | |
carry = sum / 10 | |
} else { | |
ans[i] = sum | |
carry = 0 | |
} | |
} | |
if(carry > 0) { | |
ans.add(0, carry) | |
} | |
return ans.toIntArray() | |
} | |
} |
沒有留言:
張貼留言