TCS Coding Question - Odd Even Place Sum Difference
Problem Statement:
Given a maximum of 100 digit numbers as input, find the difference between the sum of odd and even position digits
Test Cases
Case 1
Input: 4567
Expected Output: 2
Explanation : Odd positions are pos: 1 and pos: 3 which has digits 4 and 6 respectively, and both have sum 10. Similarly, even positions pos: 2 and pos: 4 with digits 5 and 7 respectively and sum 12. Thus, difference is 12 – 10 = 2
Case 2
Input: 5476
Expected Output: 2
Case 3
Input: 9834698765123
Expected Output: 1
Approach:
1. Calculate sum for digits at Odd places
2. Calculate sum for digits at even places
3. Find difference between both the Sum
4. Return result
C Progam
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
int main()
{
int oddSum = 0,evenSum = 0,i = 0, n,diff;
long long num;
scanf("%lld",&num);
while(num != 0){
if(i%2==0){
evenSum = evenSum + num%10;
num = num/10;
i++;
}
else{
oddSum = oddSum + num%10;
num = num/10;
i++;
}
}
printf("%d",abs(oddSum - evenSum));
return 0;
}
Java Program
package codingExample;
import java.util.Scanner;
public class OddEvenPositionSumDifference {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
long evenSum = 0, oddSum = 0;
for (int i = 0; i < input.length(); i++) {
if (i % 2 == 0)
evenSum = evenSum + input.charAt(i) - '0';
else
oddSum = oddSum + input.charAt(i) - '0';
}
System.out.println(Math.abs(evenSum - oddSum));
}
}
For More TCS Digital Capability Assessment solution - Click here or Here
This Blog is Hard work !
Can you give me a treat 😌
0 Comments