Thursday, 9 July 2020

Plus One : LeetCode

Given a non-empty array of 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.
Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Solution:
class Solution {
    public int[] plusOne(int[] digits) {
       int length = digits.length;
        int i=length -1;
        while(i>=0){
            if(digits[i]!=9){
                digits[i] = digits[i]+1;
                return digits;
            }
             digits[i]=0;
            i--;
            
        }
        int[] finalArr = new int[length+1];
        finalArr[0]=1;
        return finalArr;
    }
}

No comments:

Post a Comment

links for Data Structure

  1) 𝐁𝐞𝐜𝐨𝐦𝐞 𝐌𝐚𝐬𝐭𝐞𝐫 𝐒𝐧 π‹π’π§π€πžπ 𝐋𝐒𝐬𝐭:  https://lnkd.in/gXQux4zj 2) 𝐀π₯π₯ 𝐭𝐲𝐩𝐞𝐬 𝐨𝐟 π“π«πžπž π“π«πšπ―πžπ«π¬πšπ₯𝐬...