In this Leetcode Plus One problem solution, we have Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. You may assume the integer does not contain any leading zero, except the number 0 itself.

Leetcode 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;
    
     
}