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 };
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)