Plus One_LeetCode
Description:
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
解题思路:
这题题面有点难理解,大约就是一个进位函数,这个数把每一位存在数组里面,下标约靠前,所代表的位数越高。
比如9999存在这个数组里就是{9,9,9,9}的形式。
此时要加1需要考虑进位的情况。
从最低位开始遍历,只要是9,就把这位变成0,一旦遇到不是9的位数,就把这位的值+1以后就直接结束,返回数组。
此外,还需要考虑一个特殊情况,也就是首位是9的进位情况,比如999这样。
所以遍历到第一位是9就把第一位变成1并且在最后一位多加一个0。
代码:
class Solution { public: vector<int> plusOne(vector<int>& digits) { for (int i = digits.size()-1; i >= 0; i--) { if (digits[i] == 9) { if (i == 0) { digits[0] = 1; digits.push_back(0); return digits; } digits[i] = 0; } else { digits[i]+=1; return digits; } } return digits; } };
-