[LeetCode] #66 Plus One

#66 Plus One

Question

Given a non-negative integer represented as a non-empty array of digits, plus one to the integer. You may assume the integer do not contain any leading zero, except the number 0 itself. The digits are stored such that the most significant digit is at the head of the list.

Thinking

題意為給一個非整數,該數用一個陣列來表示,每個陣列值代表該數位數的值,最後我們要算出該數加1後的陣列,例如:99以[9,9]表示,加1後為100以[1,0,0]表示,而當此情形發生時,即陣列長度發生變化。這裡有個小技巧可以使用,直接宣告一陣列,並指定陣列的大小,僅將索引0的位置給1,其他位置則會被初始化為0了,例如:int test[4] = new int[] {1};這樣test會被初始化為[1,0,0,0]

My C# Solution

public class Solution {
    public int[] PlusOne(int[] digits) {
        var plus = 1;
        for (var i = digits.Length - 1; i >= 0; i--)
        {
            var digit = digits[i];
            var newDigit = digit + plus;
            if (newDigit == 10)
            {
                digits[i] = 0;
                plus = 1;
            }
            else
            {
                digits[i] = newDigit;
                plus = 0;
            }
        }
        
        if (plus == 1)
        {
            var newDigits = new int[digits.Length + 1];
            newDigits[0] = 1;
            return newDigits;
        }
        return digits;
    }
}