Home > Article > Backend Development > C program to calculate the difference between odd number of digits and even number of digits
Given a number, find the difference between the odd number of digits and the even number of digits. This means we will count all the even digits and all the odd digits and subtract their sum.
Input:12345 Output:3
the odd digits is 2+4=6 the even digits is 1+3+5=9 odd-even=9-6=3
Take each digit in the number and check if the number is even or odd, if it is even then sum it with the even number Add, if not, add with the odd sum and take the difference.
#include <iostream> using namespace std; int main() { int n, r=0; int diff =0; int even=0; int odd=0; n=12345; while(n != 0){ r = n%10; if(r % 2 == 0) { even+=r; } else { odd+=r; } n/=10; } diff=odd-even; printf("%d",diff); return 0; }
The above is the detailed content of C program to calculate the difference between odd number of digits and even number of digits. For more information, please follow other related articles on the PHP Chinese website!