Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
1.按照要求,对数组进行操作。取数组最后一位,进行加一操作。对长度为1的数组单独处理。考虑极端情况:{9,9,9,9}等。需要在数组头部添加1,这里使用动态数组。该方法通过LeetCode检测验收。
class Solution { public: vector<int> plusOne(vector<int>& digits) { int length = digits.size(); if (length == 1) { digits[0] = digits[0] + 1; if(digits[0]>9) { digits[0]=digits[0]-10; digits.insert(digits.begin(),1); } return digits; } digits[length - 1] = digits[length - 1] + 1; for (int i = length - 1; i >= 0; i--) { if (i > 0 && digits[i] > 9) { digits[i] = digits[i] - 10; digits[i - 1] = digits[i - 1] + 1; } if (i == 0 && digits[i] > 9) { digits[i] = digits[i] - 10; digits.insert(digits.begin(), 1); } } return digits; } };
2.把所给数组提取为数组,如[1,2,3]提取为123放在一个变量中。对提取的数字加一操作再按位放回原数组中。该方法受限于数组的长度:如定义int型变量存取,则数组所表示的数字最大为232-1.同理,定义为long long型则为264-1. 所以就当练个手,熟悉一下对数组的操作。
vector<int> plusOne(vector<int>& digits) { int length = digits.size(); if (length == 1) { int num = digits[length - 1] + 1; if (num>9) { digits.clear(); digits.push_back(1); digits.push_back(num - 10); } else digits[length - 1] += 1; } else { long long sum = 0; auto counter = 0; while (digits[counter] == 0) counter++; for (auto i = counter; i<length; i++) { sum += digits[i] * pow(10, length - i-1); } sum = sum + 1; digits.clear(); while (sum != 0) { auto t = sum - (sum / 10) * 10; digits.insert(digits.begin(),t); sum = sum / 10; } } return digits; } //组数法 受限于计算机的最大位数