首页 > 代码库 > LeetCode 66 Plus One

LeetCode 66 Plus One

Problem:

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.

Analysis:

十进制数按位存储于vector,现在求给该数字加1后所得数以vector表示的形式。

Summary:

简单的大数加法。

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

 

LeetCode 66 Plus One