## 一.题目描述
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);
}
};
~~~
两个运行结果:
![](https://box.kancloud.cn/2016-01-05_568bb5ebbc1d9.jpg)
![](https://box.kancloud.cn/2016-01-05_568bb5ebcb4f5.jpg)
## 四.小结
又是一道涉及位运算的题目,解决方法有多种,而且应该考虑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