
[Easy] 66. Plus One
发布日期:2021-05-07 18:21:08
浏览次数:18
分类:精选文章
本文共 1100 字,大约阅读时间需要 3 分钟。
66. Plus One
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.
Solution
Brute Force
4 ms 9.1 MB
这道题的意思就是将vector中的digits所代表的integer加1,比如说 Input = [1, 2, 9],Output = [1, 3, 0] Input = [9, 9], Output = [ 1, 0, 0] 所以,有两种情况: 1.如果某一位为9,需要置零进位 2.不为9,则不需要进位,那么直接加1,return digits[]class Solution { public: vector plusOne(vector & digits) { int n = digits.size(); for (int i = n - 1; i >= 0; --i) { if (digits[i] == 9) { digits[i] = 0; }else { digits[i]++; return digits; } } digits[0] = 1; digits.push_back(0); return digits; }};