Find mathematical patterns through observing test cases.
Problem
2544. Alternating Digit Sum
https://leetcode.cn/problems/alternating-digit-sum/
You are given a positive integer n. Each digit of n has a sign according to the following rules:
The most significant digit is assigned a positive sign.
Each other digit has an opposite sign to its adjacent digits.
Return the sum of all digits with their corresponding sign.
Iterate through string
Solution thinking
- convert int param to string;
- iterate string char by char;
- accumulate sum with specified sign;
- update sign in loop;
Code
|
|
Complexity analysis
Time
We need to iterate int n with log(n)
’s time complexity;
Space
Used an extra string with O(logn)
’s length。
Optimizaiton with math solution
Solution thinking
Closely examine the solution mentioned above, the reason why we used an extra string is we want to iterate the n from higher position(significant bit
) to lower position.
Another way to iterate the n’s position is using the remainder (modulus) operation as an approach.
BUT, this way leads to a new question: we need to determine the sign.
By observing the test cases, we can find the mathematical patterns:
the sign differs between the oddness or evenness of the number of digits in a specific number n
.
As illustrated in above picture, we can count the number of digits in n. And for even number, we can just calculate the opposite result sum.
For code simplicity, we can multiply -sign
at the end.
Code
|
|
Complexity analysis
Time
Time complexity is O(log(n))
.
Space
In this solution, there is no extra variable. That is the optimization point.
Space complexity is O(1)
.
Summary
At this point, the question is solved.
By solving this problem, we find the mathematical patterns through observing test cases.
- odd n: sign to left == sign to right
- even n: sign to left == opposite(sign to right)
Observing test cases is so IMPORTANT!