Efficient Algorithm to Calculate 3n (100 < n < 10000) with O(n) Time Complexity
(a) The naive calculation method to compute 3n would be to simply multiply n by 3. This can be done in O(1) time complexity as it involves a single multiplication operation.
(b) To calculate 3n with a time complexity not exceeding O(n), we can use the following algorithm:
- Convert n to a string.
- Initialize a result string with a length equal to the length of the input string plus one.
- Iterate through each digit in the input string from right to left. a. Convert the digit to an integer and multiply it by 3. b. Add the result of the multiplication to the corresponding digit in the result string. c. If the result is greater than or equal to 10, subtract 10 from the result and add 1 to the next left digit in the result string.
- Convert the result string to an integer and return it as the final result.
The time complexity of this algorithm is O(n) because we iterate through each digit in the input string exactly once.
Example: Let's say n = 1234.
- Convert n to a string: '1234'.
- Initialize result string: '0000'.
- Iterating through each digit from right to left: a. Digit 4: Multiply by 3 -> 12. Add to result string: '0012'. b. Digit 3: Multiply by 3 -> 9. Add to result string: '0092'. c. Digit 2: Multiply by 3 -> 6. Add to result string: '0062'. d. Digit 1: Multiply by 3 -> 3. Add to result string: '0032'.
- Convert result string to an integer: 32. Return as the final result.
原文地址: https://www.cveoy.top/t/topic/UK3 著作权归作者所有。请勿转载和采集!