plus-one.dart (952B)
1 //Add one to the last index of the array. If needed carry the value on to the next 2 //value on the left. My implementation has a worst case time complexity of O(n) 3 //because at most it only iterates through the list one time. 4 5 //Execution: 265ms Beats: 71.43% 6 //Memory: 142MB Beats: 86.55% 7 8 9 10 void main(){ 11 Solution sol = new Solution(); 12 print(sol.plusOne([3,9,9,9,9,9])); 13 } 14 class Solution { 15 List<int> plusOne(List<int> digits) { 16 int carry = 0; 17 digits[digits.length - 1] = digits[digits.length - 1] + 1; 18 for(int i = digits.length - 1; i >= 0 ; --i){ 19 if(carry != 0){ 20 digits[i] = digits[i] + carry; 21 carry = 0; 22 } 23 if(digits[i] >= 10){ 24 digits[i] -= 10; 25 carry += 1; 26 } 27 if(carry == 0){ 28 return digits; 29 } 30 } 31 if(carry != 0){ 32 digits.insert(0, carry); 33 } 34 return digits; 35 } 36 }