C# - look for first non 9 from the tail backwards


  • 0
    public int[] PlusOne(int[] digits) 
    {
        int index = digits.Length - 1;
        while (index >= 0 && digits[index] == 9)
        {
            index--;
        }
        
        if (index < 0)
        {
            int[] res = new int[digits.Length + 1];
            res[0] = 1;
            return res;
        }
        else
        {
            digits[index++]++;
            while (index < digits.Length)
            {
                digits[index++] = 0;
            }
            return digits;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.