Oddly even– TCS NQT Question 2
Calculate the absolute difference between the sum of digits at odd and even positions in a large number
Understand the Problem
Problem Statement
Given a maximum of 100-digit number as input, find the difference between the sum of digits at odd positions and the sum of digits at even positions.
Note: Positions are counted from left to right, starting with position 1 as odd.
Constraints
- The input number can have up to 100 digits
- The number can be very large, so string processing is recommended
- Position counting starts from 1 (leftmost digit is at odd position)
- Output should be the absolute difference between sums
Examples
45672Odd positions (1st and 3rd): digits 4 and 6, sum = 4 + 6 = 10. Even positions (2nd and 4th): digits 5 and 7, sum = 5 + 7 = 12. Difference = |12 - 10| = 2.
54762Odd positions (1st and 3rd): digits 5 and 7, sum = 5 + 7 = 12. Even positions (2nd and 4th): digits 4 and 6, sum = 4 + 6 = 10. Difference = |10 - 12| = 2.
98346987651231Odd positions: 9+3+6+8+6+1+3 = 36. Even positions: 8+4+9+7+5+2 = 35. Difference = |35 - 36| = 1.
Solution
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
char num[101];
fgets(num, sizeof(num), stdin);
int odd_sum = 0, even_sum = 0;
int len = strlen(num);
// Remove newline character if present
if (num[len-1] == '\n') {
num[len-1] = '\0';
len--;
}
for (int i = 0; i < len; i++) {
int digit = num[i] - '0';
// Position in string is i, but position counting starts at 1
// So index 0 corresponds to position 1 (odd)
if (i % 2 == 0) {
odd_sum += digit;
} else {
even_sum += digit;
}
}
int difference = abs(odd_sum - even_sum);
printf("%d\n", difference);
return 0;
}C Solution Explanation:
- Read the input number as a string using fgets() to handle large numbers
- Calculate string length and remove trailing newline character
- Iterate through each character in the string
- Convert character to integer by subtracting '0'
- Use array index to determine position: even indices (0,2,4...) are odd positions (1,3,5...)
- Add digits to respective sums based on position
- Calculate absolute difference using abs() function
- Print the result
This approach efficiently handles very large numbers by processing them as strings rather than attempting to convert to numeric types.