Leetcode notes: Plus One
I. Description
Given a number represented as an array of digits, plus one to the number.
Ii. Question Analysis
A high-precision computing question, from low to high for calculation, while considering the carry problem, if the highest bit calculation result has a carry, you need to add a bit before the highest bit. The time complexity is O (n) and the space complexity is O (1 ).
This question should be a simplified version, because it is only required to add 1 to a number. If any bitwise operation has no carry-in, the carry-in process is not required for a higher level, and the result can be output directly.
Iii. instance code
# Include
# Include
Using namespace std; class Solution {public: void plusOne (vector
& 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) // if the highest bit operation still has a forward digit, you need to add a union of 1 digits. insert (digits. begin (), carry );}};
Two running results:
Iv. Summary
It is also a problem involving bit operations. There are many solutions, and we should consider what to do when the plus value is different.