## 一.題目描述
Given a number represented as an array of digits, plus one to the number.
## 二.題目分析
一道高精度計算的題,從低位到高位進行計算,同時考慮進位的問題,若最高位計算結果還有進位,就需要在最高位前面添加一位。可做到時間復雜度為O(n),空間復雜度為O(1)。
這道題應該算是簡化版,因為要求只是對一個數加1,如果任何一位的運算沒有進位,則更高位也不需要進行進位處理了,可以直接輸出結果。
## 三.實例代碼
~~~
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
void plusOne(vector<int>& digits)
{
int carry = 1;
const int digitsSize = digits.size();
for (int i = digitsSize - 1; i >= 0; i--)
{
digits[i] += carry;
if (digits[i] < 10)
{
carry = 0;
break;
}
carry = digits[i] / 10;
digits[i] %= 10;
}
if (carry != 0) // 若最高位運算仍有進位,則需新增一位并置1
digits.insert(digits.begin(), carry);
}
};
~~~
兩個運行結果:


## 四.小結
又是一道涉及位運算的題目,解決方法有多種,而且應該考慮plus不同的值時,又該怎么處理。
- 前言
- 2Sum
- 3Sum
- 4Sum
- 3Sum Closest
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II
- Search in Rotated Sorted Array
- Remove Element
- Merge Sorted Array
- Add Binary
- Valid Palindrome
- Permutation Sequence
- Single Number
- Single Number II
- Gray Code(2016騰訊軟件開發筆試題)
- Valid Sudoku
- Rotate Image
- Power of two
- Plus One
- Gas Station
- Set Matrix Zeroes
- Count and Say
- Climbing Stairs(斐波那契數列問題)
- Remove Nth Node From End of List
- Linked List Cycle
- Linked List Cycle 2
- Integer to Roman
- Roman to Integer
- Valid Parentheses
- Reorder List
- Path Sum
- Simplify Path
- Trapping Rain Water
- Path Sum II
- Factorial Trailing Zeroes
- Sudoku Solver
- Isomorphic Strings
- String to Integer (atoi)
- Largest Rectangle in Histogram
- Binary Tree Preorder Traversal
- Evaluate Reverse Polish Notation(逆波蘭式的計算)
- Maximum Depth of Binary Tree
- Minimum Depth of Binary Tree
- Longest Common Prefix
- Recover Binary Search Tree
- Binary Tree Level Order Traversal
- Binary Tree Level Order Traversal II
- Binary Tree Zigzag Level Order Traversal
- Sum Root to Leaf Numbers
- Anagrams
- Unique Paths
- Unique Paths II
- Triangle
- Maximum Subarray(最大子串和問題)
- House Robber
- House Robber II
- Happy Number
- Interlaving String
- Minimum Path Sum
- Edit Distance
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock II
- Best Time to Buy and Sell Stock III
- Best Time to Buy and Sell Stock IV
- Decode Ways
- N-Queens
- N-Queens II
- Restore IP Addresses
- Combination Sum
- Combination Sum II
- Combination Sum III
- Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Preorder and Inorder Traversal
- Longest Consecutive Sequence
- Word Search
- Word Search II
- Word Ladder
- Spiral Matrix
- Jump Game
- Jump Game II
- Longest Substring Without Repeating Characters
- First Missing Positive
- Sort Colors
- Search for a Range
- First Bad Version
- Search Insert Position
- Wildcard Matching