Here’s the code to my attempt to solve PlusOne on LeetCode. Any simplifications, tips or pointers are greatly appreciated!
Problem Prompt:
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.
input examples: [3, 4, 9], [0], [9], [6, 2] public class Solution { public int[] PlusOne(int[] digits) { if (digits[0] == 0) { digits[0] = 1; return digits; } int carry = 0; for (var i = digits.Length - 1; i >= 0; i--) { digits[i] = digits[i] + carry; if (digits[i] == digits[digits.Length - 1]) { digits[i] = digits[i] + 1; } if (digits[i] > 9) { digits[i] = 0; carry = 1; } } if (carry > 0) { int[] newDigits = new int[digits.Length + 1]; newDigits[0] = 1; for (var j = 1; j < newDigits.Length; j++) { newDigits[j] = digits[j -1]; } return newDigits; } return digits; } }
Edit: Current issue Input: [1,0] Output: [2,1] Expected: [1,1]