首页 > 学院 > 开发设计 > 正文

66. Plus One

2019-11-06 08:49:24
字体:
来源:转载
供稿:网友

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.

还是先翻译题目:

给定一个用非空数组表示的非负整数,对该整数加一,输出新的用数组表示的整数;

这道题倒是不难,但是一直没有通过是因为没有掌握vector的用法,将vector当作是一个数组名然后直接

vector[size+1]=0;

是在这里出现了错误,一直都是在用例[9]那里无法通过;

还有一个没搞清的问题是之前写的另外一份出现了超时,对于超时还需要研究;

以下为解题思路:

由于数组第一位表示的是整数的高位,以此类推,所以先从数组的最后一位开始判断,

如果是9,那么就加一,变为0,对其赋值为0,然后接着判断其前面一位,如果不是9,则该位加一,

然后退出循环;

然后判断是否出现全9的情况,如果出现全9,那么第一位必然是0,判断第一位是否为0,若是,则将其赋值为

1,然后在末位加一个0;

以下为代码示例:

class Solution {public:    vector<int> plusOne(vector<int>& digits) {        int i,j,temp;        bool k;        j=digits.size();        j--;        for(int i=j;i>=0;i--){            if(digits[i]==9){                digits[i]=0;                continue;            }            else{                temp=digits[i];                temp++;                digits[i]=temp;                break;            }        }        if(digits[0]==0){            digits[0]=1;            //temp=j;            //temp++;            digits.push_back(0);        }        return digits;    }};class Solution {public:vector<int> plusOne(vector<int>& digits) {int i,j,temp;bool k;j=digits.size();j--;for(int i=j;i>=0;i--){if(digits[i]==9){digits[i]=0;continue;}else{temp=digits[i];temp++;digits[i]=temp;break;}}if(digits[0]==0){digits[0]=1;//temp=j;//temp++;digits.push_back(0);}return digits;}};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表