Write a java program to calculate the sum of odd and even digits in a number. The input consists of a single integer ‘n’ which corresponds to the given number.The output must display the sum of odd numbers and even numbers.
Problem Constraints:
The datatype of integer must be long.
The file name must be Main.java
Sample Input and Output :
Enter the number
3924209420352
The sum of the odd digits are 29
The sum of the even digits are 16
Solution
import java.util.*;
class Main{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
long n = sc.nextLong();
// sauravhathi
long odd = 0;
long even = 0;
while(n!=0){
long rem = n%10;
if(rem%2==0){
even = even + rem;
}
//sauravhathi
else{
odd = odd + rem;
}
n = n/10;
}
System.out.println("The sum of the odd digits are "+odd);
System.out.println("The sum of the even digits are "+even);
}
// sauravhathi
}
#include <iostream>
using namespace std;
int main() {
long n;
cin >> n;
long odd = 0;
long even = 0;
while(n!=0){
long rem = n%10;
if(rem%2==0){
even = even + rem;
}
//sauravhathi
else{
odd = odd + rem;
}
n = n/10;
}
cout << "The sum of the odd digits are " << odd << endl;
cout << "The sum of the even digits are " << even << endl;
return 0;
}
n = int(input())
odd = 0
even = 0
// sauravhathi
while n != 0:
rem = n % 10
if rem % 2 == 0:
even += rem
else:
odd += rem
n //= n / 10
print("The sum of the odd digits are", odd)
// sauravhathi
print("The sum of the even digits are", even)
Happy Learning – If you require any further information, feel free to contact me.