题目:http://oj.leetcode.com/problems/plus-one/
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.
题目翻译:
给定一个数字数组表示的非负数,对该数加1。
最高位数字存储在列表的头部。
分析:
从后向前处理。如果不再有进位,则可以跳出循环。如果最高位产生了进位需要在数组的头部插入1。
C++实现:
class Solution {
public:
vector<int> plusOne(vector<int> &digits) {
int carry = 1;
int i = digits.size() - 1;
for(; i >= 0; --i)
{
digits[i] += carry;
if(digits[i] >= 10)
{
digits[i] -= 10;
carry = 1;
}
else
{
carry = 0;
break;
}
}
if(i == -1 && carry == 1)
{
digits.insert(digits.begin(), 1);
}
return digits;
}
};
Java实现:
public class Solution {
public int[] plusOne(int[] digits) {
int carry = 1;
int i = digits.length - 1;
for (; i >= 0; --i) {
digits[i] += carry;
if (digits[i] >= 10) {
digits[i] -= 10;
carry = 1;
} else {
carry = 0;
break;
}
}
if (i < 0) {
int[] result = new int[digits.length + 1];
result[0] = 1;
System.arraycopy(digits, 0, result, 1, digits.length);
return result;
} else {
return digits;
}
}
}
Python实现:
class Solution:
# @param digits, a list of integer digits
# @return a list of integer digits
def plusOne(self, digits):
carry = 1
for j in range(len(digits) - 1, -1, -1):
digits[j] += carry
if digits[j] >= 10:
digits[j] -= 10
carry = 1
else:
carry = 0
break
if j == 0 and carry == 1:
digits.insert(0, 1)
return digits
感谢阅读,欢迎评论!