題目描述:
Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
分析:
題意: 給定一個非空非負整型數組(不存在前置零),把它看成一個數字,返回加一之後對應的結果。
思路:這是一道普通的字符串加法題的變種,假設數組大小爲n,我們按照n - 1→0,對每個數字進行加法運算,用num表示更新之後的值,用carry表示當前位對前一位的進位。注意一點:如果最高位進行加法運算之後有進位,那麼在數組最前面插入1。
時間複雜度爲O(n)。
代碼:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
int n = digits.size();
// Exceptional Case:
if(n == 0){
digits.push_back(1);
return digits;
}
int num = 0, carry = 1;
for(int i = n - 1; i >= 0; i--){
num = (digits[i] + carry) % 10;
carry = (digits[i] + carry) / 10;
digits[i] = num;
if(!carry){
return digits;
}
}
if(carry){
digits.insert(digits.begin(), carry);
}
return digits;
}
};