Title: 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 this most significant is in the head of the list.
Title translation:
Given a non-negative number represented by a numeric array, add 1 to the number.
The highest digit number is stored in the head of the list.
Analysis:
Processing from the back forward. If you no longer have a carry, you can jump out of the loop. If the highest bit produces a carry need to insert 1 in the head of the array.
C + + implementation:
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] >=)
{
digits[i] =;
carry = 1;
}
else
{
carry = 0;
break;
}
}
if (i = = 1 && carry = 1)
{
Digits.insert (Digits.begin (), 1);
}
return digits;
}
;
Java implementation:
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] >=) {
digits[i] =;
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 implementations:
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] =
carry = 1
else:
carry = 0 Break
If J = 0 and carry = = 1:
digits.insert (0, 1) return
digits
Thank you for reading and welcome comments.