Difference – Sum of Odd and Even Digits

Given a maximum of hundred digits as the input. The program must print the difference between the sum of odd and even digits as the output. If the input is not a valid number, then print Invalid as the output.

Example Input/Output 1:
Input:
118745913

Output:
15

Explanation:
The sum of odd digits is 27 (1, 1, 7, 5, 9, 1 and 3).
The sum of even digits is 12 (8 and 4).
So the difference is 27-12 = 15.
Hence the output is 15

Example Input/Output 2:
Input:
235468173645

Output:
-6

Example Input/Output 3:
Input:
76320Afk384

Output:
Invalid

Note: The invalid number may contain white spaces.

#include<stdio.h>

int main()
{
    char str[1000];
    scanf("%[^n]s",str);

    int len=strlen(str),flag=0,even=0,odd=0;

    for(int i=0;i<len;i++)
    {
        if(isalpha(str[i]) || str[i]==' ' || isalnum(str[i])==0)
        {
            flag=1;
            break;
        }

        int a=str[i]-48;

        if(a%2==0)
        {
            even=even+a;
        }
        else
        odd=odd+a;

    }

    if(flag==1)
    {
        printf("Invalid");
    }
    else
    {
        printf("%d",odd-even);
    }

}
s = input().strip()

if not s.isdigit():
    print("Invalid")
else:
    odd_sum = sum(int(ch) for ch in s if int(ch) % 2 == 1)
    even_sum = sum(int(ch) for ch in s if int(ch) % 2 == 0)
    print(odd_sum - even_sum)
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s;
    getline(cin, s);

    int odd_sum = 0, even_sum = 0;
    bool isValid = true;

    for(char ch : s) {
        if(!isdigit(ch)) {
            isValid = false;
            break;
        }
        int digit = ch - '0';
        if(digit % 2 == 0) {
            even_sum += digit;
        } else {
            odd_sum += digit;
        }
    }

    if(isValid) {
        cout << odd_sum - even_sum;
    } else {
        cout << "Invalid";
    }
    return 0;
}
import java.util.Scanner;

public class OddEvenDifference {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();

        int odd_sum = 0, even_sum = 0;
        boolean isValid = true;

        for(char ch : s.toCharArray()) {
            if(!Character.isDigit(ch)) {
                isValid = false;
                break;
            }
            int digit = ch - '0';
            if(digit % 2 == 0) {
                even_sum += digit;
            } else {
                odd_sum += digit;
            }
        }

        if(isValid) {
            System.out.println(odd_sum - even_sum);
        } else {
            System.out.println("Invalid");
        }
    }
}
Previous Article

Consonant - Vowel Pairs

Next Article

Function numberTrianglePattern - CTS PATTERN

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *