classSolution { public: vector<int> plusOne(vector<int>& digits){ int i = digits.size() - 1; while (i >= 0 && digits[i] == 9 ) i--; for (int j = i + 1; j < digits.size() ; j++ ) digits[j] = 0; if (i == -1) digits.insert(digits.begin(),1); else digits[i] += 1; return digits; } };
Python3 代码
1 2 3 4 5 6 7 8 9 10 11 12
classSolution: defplusOne(self, digits: List[int]) -> List[int]: i = len(digits) - 1 while digits[i] == 9and i >= 0: i = i - 1 for j in range(i + 1,len(digits)): digits[j] = 0 if i == -1: digits.insert(0,1) else: digits[i] += 1 return digits