leetcode Plus ONE

来源:互联网 发布:java模拟 qq加好友 编辑:程序博客网 时间:2024/06/05 04:13
Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

分析:这是一个进位加法运算,设置进位变量add,初始值1,判断最低位加1后是否满10,满10则add=1,否则=0;如此循环。直至结束:

    vector<int> plusOne(vector<int>& digits) {        int i;int sum=0;int add=1;vector<int>a(digits.size(),0);for(i=digits.size()-1;i>=0;i--){sum=digits[i]+add;add=sum/10;a[i]=sum%10;}if(add==1)a.insert(a.begin(),add);return a;    }


0 0
原创粉丝点击