Hello, everyone. Today, I would like to share with you the next simple difficulty problem of LeetCode [plus one].
Given a non-negative integer represented by a non-empty array of integers, add one to that number.
The highest digit is stored at the beginning of the array, and only a single digit is stored for each element of the array.
You can assume that the integer does not start with zero except the integer 0.
The title
Example 1: Input: digits = [1,2,3] Output: [1,2,4] Explanation: The input array represents the number 123. Example 2: input: digits = [4,3,2,1] output: [4,3,2,2] explanation: the input array represents the number 4321. Example 3: Input: digits = [0] Output: [1]Copy the code
Analysis of the
1. An integer is broken up into an array
2. If an integer is added by 1, it needs to be carried if it ends in 9
solution
1. The iteration
Solution a:The iteration
Train of thought1.Iterate backwards2.modulo3.If I take mod PI0I'm going to keep going1But if you encounter the first position is0, you need to add one digit before the array1* /var plusOne = function (digits) {
for (let i = digits.length - 1; i >= 0; i--) {
digits[i] = (digits[i] + 1) % 10;
if(digits[i] ! = =0) {
break;
} else {
// Add one digit before the array if it is already the first bit
if (i === 0) {
digits.unshift(1); }}}return digits;
};
/* The minimum complexity time is O(n), and the maximum complexity is O(1) */ for 2n space
Copy the code
conclusion
This problem examines the application of pairs of arrays to pairs of iterations
You can look at a column I share (front-end algorithm) there are more questions about the algorithm to share, I hope to help you, I will try to keep updated every night, if you like the trouble to help me a like, thank you very much
The purpose of this article is to study, discuss and share the experience in the process of learning algorithm. Part of the material in this article comes from the network. If there is infringement, please contact delete, [email protected]