Posts Plus One
Post
Cancel

Plus One

This question is part of NeetCode150 series.

Problem Description

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.

leetcode

Solution

We can start from right to left. Carry will be initialized to 0. The next digit in the answer will be (current digit in N + carry). For right most digit, we will need to add 1 also since the problem is about adding 1 to N. At the end, if any carry is remaining, append that to the answer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {

    public int[] plusOne(int[] digits) {

        StringBuffer result = new StringBuffer();

        int carry = 0;

        for(int i=digits.length-1; i>=0; i--){
            
            int s = 0;

            if(i == digits.length-1){
                s = 1 + digits[i] + carry;
            }else{
                s = digits[i] + carry;
            }

            int next = s%10;
            carry = s/10;
            
            result.insert(0, next);

        }

        if(carry > 0) result.insert(0, carry);

        System.out.print(result);

        String[] temp = result.toString().split("");
        int[] ans = new int[temp.length];

        for(int i=0; i<ans.length; i++){
            ans[i] = Integer.parseInt(temp[i]);
        }

        return ans;

    }

}
This post is licensed under CC BY 4.0 by the author.