Java Program for Difference between sums of odd and even digits
Last Updated :
20 Oct, 2023
Write a java program for a given long integer, the task is to find if the difference between sum of odd digits and sum of even digits is 0 or not. The indexes start from zero (0 index is for leftmost digit).
Examples:
Input : 1212112
Output : Yes
Explanation:
the odd position element is 2+2+1=5
the even position element is 1+1+1+2=5
the difference is 5-5=0 equal to zero.
So print yes.
Input :12345
Output : No
Explanation:
the odd position element is 1+3+5=9
the even position element is 2+4=6
the difference is 9-6=3 not equal to zero.
So print no.
Approach:
One by one traverse digits and find the two sums. If difference between two sums is 0, print yes, else no.
Below is the implementation of the above approach:
Java
public class Main {
public static boolean isDiff0( int n)
{
int first = 0 ;
int second = 0 ;
boolean flag = true ;
while (n > 0 ) {
int digit = n % 10 ;
if (flag) {
first += digit;
}
else {
second += digit;
}
flag = !flag;
n = n / 10 ;
}
if (first - second == 0 ) {
return true ;
}
return false ;
}
public static void main(String[] args)
{
int n = 1243 ;
if (isDiff0(n)) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
}
|
Time Complexity:O(log n)
Auxiliary space: O(1)
Please refer complete article on Difference between sums of odd and even digits for more details!
Share your thoughts in the comments
Please Login to comment...