easy
0 views

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

Example 1
Input
4567
Output
2
Explanation

Odd 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.

Example 2
Input
5476
Output
2
Explanation

Odd 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.

Example 3
Input
9834698765123
Output
1
Explanation

Odd 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;
}
Time:O(n) where n is the number of digits
Space:O(1) - only using a fixed-size string buffer and a few integer variables
Approach:

C Solution Explanation:

  1. Read the input number as a string using fgets() to handle large numbers
  2. Calculate string length and remove trailing newline character
  3. Iterate through each character in the string
  4. Convert character to integer by subtracting '0'
  5. Use array index to determine position: even indices (0,2,4...) are odd positions (1,3,5...)
  6. Add digits to respective sums based on position
  7. Calculate absolute difference using abs() function
  8. Print the result

This approach efficiently handles very large numbers by processing them as strings rather than attempting to convert to numeric types.

Visual Explanation

Loading diagram...