Here, we will see how to solve Alternating Digit Sum Solution of leet code 2544 problem.
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.
You have to return the sum of all digits with their corresponding sign.
Example 1:
Input: num = 123 Output: 2 Explanation: (+1) + (-2) + (+3) = 2
Example 2:
Input: num = 886996 Output: 0 Explanation: (+8) + (-8) + (+6) + (-9) + (+9) + (-6) = 0.
Alternating Digit Sum Solution in C++:
Here, we will be solving problem in multiple ways with code.
C++ code 1:
class Solution {
public:
int alternateDigitSum(int n) {
int k = 1, ans = 0;
while(n>0)
{
ans += (n%10) * k;
n = n / 10;
k *= -1;
}
return -k * ans;
}
};
C++ code 2:
class Solution {
public:
int alternateDigitSum(int n) {
int total_digit = 0, tmp = n, sign, sum = 0;
while(tmp) {
total_digit += 1;
tmp /= 10;
}
if (total_digit % 2 == 1) {
sign = 1;
} else {
sign = -1;
}
while(n) {
sum += (n % 10) * sign;
n /= 10;
sign *= -1;
}
return sum;
}
};
Output:
Input: n = 111 Output: 1 Explanation: (+1) + (-1) + (+1) = 1.
Time complexity: O(n)
Space complexity: O(1)
To check more leetcode problem’s solution. Pls click given below link:
https://www.techieindoor.com/category/leetcode/
https://www.techieindoor.com/category/interview-questions/