66. Plus One
1. 问题描述
Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
Subscribe to see which companies asked this question
Tags: Array Math
Similar Problems: (M) Multiply Strings (E) Add Binary
2. 解答思路
3. 代码
1 #include <vector> 2 using namespace std; 3 class Solution { 4 public: 5 vector<int> plusOne_method_1(vector<int>& digits) { 6 if (digits.empty()) 7 { 8 digits.push_back(1); 9 return digits; 10 } 11 return puls(digits, digits.size()-1, 1); 12 } 13 vector<int> plusOne_method_2(vector<int>& digits) { 14 if (digits.empty()) 15 { 16 digits.push_back(1); 17 return digits; 18 } 19 int nTakeOver = 1; 20 int i; 21 for (i=digits.size()-1; i>=0; i--) 22 { 23 int sum = digits[i] + nTakeOver; 24 digits[i] = sum%10; 25 nTakeOver = sum/10; 26 if (0 == nTakeOver) 27 { 28 return digits; 29 } 30 } 31 if (1 == nTakeOver) 32 { 33 digits.insert(digits.begin(), 1); 34 } 35 return digits; 36 } 37 private: 38 vector<int> puls(vector<int>& digits, int idx, int nTakeOver = 0) 39 { 40 int sum = digits[idx] + nTakeOver; 41 digits[idx] = sum%10; 42 nTakeOver = sum/10; 43 if (0 == nTakeOver) 44 { 45 return digits; 46 } 47 if (0 == idx) 48 { 49 digits.insert(digits.begin(), 1); 50 return digits; 51 } 52 return puls(digits, idx-1, 1); 53 } 54 };
4. 反思
方法1. 递归实现
方法2. 循环实现