C# solution: array and carry


  • 0
    B
    public class Solution 
    {
        public int[] PlusOne(int[] digits) 
        {
            var n = digits.Length;
    
            var result = new List<int>();
            
            if (n == 0) return result.ToArray();
    
            var carry = 0;
    
    
            for (int i = n - 1; i >= 0; i--)
            {
                var tempResult = digits[i] + carry;
                if (i == n - 1)
                {
                    tempResult += 1;
                }
    
                carry = tempResult / 10;
                result.Insert(0, tempResult % 10);
            }
    
            if (carry != 0) result.Insert(0, carry);
    
            return result.ToArray();
        }
    }
    

Log in to reply
 

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