Leetcode 2544. Alternating Digit Sum
You are given a positive integer n
. Each digit of n
has a sign according to its position:
Return the sum of all digits of n
with their respective signs.
Example:
Input: n = 521
Output: 5 - 2 + 1 = 4
Input: n = 111
Output: 1 - 1 + 1 = 1
n
?
n
is a positive integer.n
?
n
fits within the standard 32-bit integer range (1 to (2^{31}-1)).n
to a string to easily access each digit by its position.#include <iostream>
#include <string>
using namespace std;
int alternatingDigitSum(int n) {
string numStr = to_string(n);
int length = numStr.length();
int sum = 0;
for (int i = 0; i < length; ++i) {
// Convert character digit to integer
int digit = numStr[i] - '0';
// Apply sign base on the position index
if (i % 2 == 0) {
sum += digit; // Positive for even index
} else {
sum -= digit; // Negative for odd index
}
}
return sum;
}
// Example usage
int main() {
int n = 521;
cout << "The alternating digit sum of " << n << " is: " << alternatingDigitSum(n) << endl;
return 0;
}
n
. The conversion of n
to a string and the iteration through each digit both operate within linear time relative to the number of digits.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?