Plus One Problem: You are given a large integer represented as an integer array digits
, where each digits[i]
is the ith
digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0
‘s.
Increment the large integer by one and return the resulting array of digits.
Example :
Input: digits = [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Incrementing by one gives 123 + 1 = 124. Thus, the result should be [1,2,4].
Table of Contents
Plus One Problem Solution
Problem Solution In Python
class Solution(object):
def plusOne(self, digits):
digits=str(int(''.join([str(x) for x in digits]))+1)
ret=[]
for i in range(len(digits)):
ret.append(int(digits[i:i+1]))
return ret
Problem Solution In Java
class Solution {
public int[] plusOne(int[] digits) {
int carry = 1;
for (int i = digits.length - 1; i >= 0; i--) {
int sum = digits[i] + carry;
carry = sum / 10;
digits[i] = sum % 10;
}
if (carry > 0) {
int[] sum = new int[digits.length + 1];
sum[0] = carry;
for (int i = 1; i < sum.length; i++)
sum[i] = digits[i - 1];
return sum;
} else
return digits;
}
}
Problem Solution In C++
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
vector<int>res;
int size=digits.size();
if(size==0)return res;
int pos=size-1, carry=0, sum;
while(pos>=0 || carry==1){
sum=digits[pos] + carry;
if(pos==size-1)sum=sum+1;
carry=(sum>=10)?1:0;
sum=sum%10;
res.insert(res.begin(),sum);
pos--;
}
return res;
}
};
Problem Solution In C
int* plusOne(int* digits, int digitsSize, int* returnSize){
for(int i=digitsSize-1;i>=0;i--)
{
if(digits[i]==9)
{
digits[i]=0;
}
else{
digits[i]+=1;
* returnSize=digitsSize;
return digits;
}
}
* returnSize=++digitsSize;
int* result = malloc(digitsSize * sizeof(int));
for(int i=1;i<digitsSize;i++)
{
result[i]=0;
}
result[0]=1;
return result;
}