LeetCode66 Plus One

Posted wangxiaobao的博客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode66 Plus One相关的知识,希望对你有一定的参考价值。

题目:

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.(Easy)

分析:

基本的加法操作,用carry处理进位即可,注意最后多一位的时候insert一个1。

代码:

 1 class Solution {
 2 public:
 3     vector<int> plusOne(vector<int>& digits) {
 4         int carry = 0;
 5         digits[digits.size() - 1]++;
 6         for (int i = digits.size() - 1; i >= 0; --i) {
 7             int temp = digits[i] + carry;
 8             if (temp == 10) {
 9                 carry = 1;
10                 temp = 0;
11             }
12             else {
13                 carry = 0;
14             }
15             digits[i] = temp;
16         }
17         if (carry == 1) {
18             digits.insert(digits.begin(), 1);
19         }
20         return digits;
21     }
22 };

 

以上是关于LeetCode66 Plus One的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode-66 Plus One

leetcode 66. Plus One

[LeetCode] 66. Plus One

[leetcode]66.Plus One

leetcode66 Plus One

[leetcode]66Plus One