随笔- 509  文章- 0  评论- 151  阅读- 22万 

Plus One

2013.12.22 03:37

Given a number represented as an array of digits, plus one to the number.

 

Solution:

  This problem seems quite easy, right? See if you can AC with one shot.

  Here're some good test cases for you:

    0 + 1 = 1

    1 + 1 = 2

    34 + 1 = 35

    99 + 1 = 100

  Note that we write the number "100" in the order '1','0','0', it's stored as ['1', '0', '0']. Don't make it 001.

  Time compelxity is O(n), where n is the length of the string.Space compelxity is O(1).

Accepted code:

复制代码
 1 // 3WA, 1AC
 2 class Solution {
 3 public:
 4     vector<int> plusOne(vector<int> &digits) {
 5         // IMPORTANT: Please reset any member data you declared, as
 6         // the same Solution instance will be reused for each test case.
 7         
 8         int i, len;
 9         len = digits.size();
10         
11         if(len <= 0){
12             return digits;
13         }
14         
15         // 1WA here, add 1 at the wrong position, you FOOL!!!
16         ++digits[len - 1];
17         // 1WA here, reversed order..
18         for(i = len - 1; i > 0; --i){
19             digits[i - 1] += digits[i] / 10;
20             digits[i] %= 10;
21         }
22         // 1WA here, carry propagation here neglected..
23         if(digits[0] >= 10){
24             int tmp = digits[0] / 10;
25             digits[0] %= 10;
26             digits.push_back(0);
27             for(i = len; i > 0; --i){
28                 digits[i] = digits[i - 1];
29             }
30             digits[0] = tmp;
31         }
32         
33         return digits;
34     }
35 };
复制代码

 

 posted on   zhuli19901106  阅读(238)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示