TCS NQT Oddly Even Coding Question Solution

Oddly Even TCS NQT

Given a maximum of 100 digit numbers as input, find the difference between the sum of odd and even position digits.

Input :

 4567

Expected output: 

2

Explanation

Here, the sum of odd position digits 4 and 6 is 10. The Sum of even position digits 5 and 7 is 12. The difference is 12-10 = 2.


Logic

  • Take input as string hence you can check the position of digit is odd or even.
  • Take variable to store odd position sum and even position sum.
  • In loop check each position is even or odd.
  • If digit is on odd place add to s1.
  • If digit is on even place add to s2.
  • After the complete execution of loop substract s1 from s2. 
  • Take absolute difference for positive output.
  • Print the output.

Code

#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s;                                         //take input as string
    cin >> s;
    
    int s1 = 0;                                     //to store odd number sum
    int s2 = 0;                                     //to store even number sum
    
    int l = s.length();                         //to store the length of string for loop
    
    for(int i = 0;i < l;i++){         //from 0 to size(length)
        if(i % 2 != 0){                 //if odd add to s1
            s1 = s1 + int(s[i]);
        }
        else{                 //if even add to s2
            s2 = s2 + int(s[i]);
        }
    }
    cout << abs(s1-s2);                 //print the difference
    return 0;
}

Input

4567


Output

2

Post a Comment

0 Comments