PlusOne

来源:互联网 发布:光大证券mac版 编辑:程序博客网 时间:2024/05/16 06:26

Plus One

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.

题意理解

给你一个数字以顺序结构存储每一位的数字,并且首数字不为0例如

12345 means [1,2,3,4,5]   

对这个数字进行+1操作,返回计算结果值

解题思路

首先,数字存储是反向的,数字的高位在数组的地位,因此是反向遍历;
其次,设置一个进位,初始值为1,作为+1的数值,在遍历完成后判断进位标识符是否为1,若是,则在顺序结构的头部插入一个1

代码如下

 
vector plusOne(vector& digits) {
int carry = 1;
int len = digits.size();
for (int i = len - 1; i >= 0; i–){
int t = digits[i] + carry;
digits[i] = t % 10;
carry = t / 10;
}
if (carry != 0){
digits.insert(digits.begin(), 1);
}
return digits;
}

0 0
原创粉丝点击