Open In App

Difference between Sums of Odd and Even Digits in Python

Last Updated : 20 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Write a python program for a given long integer, we need 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 the 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 the difference between two sums is 0, print yes, else no.

Python




# Python program for the above approach
def isDiff0(n):
    first = 0
    second = 0
    flag = True
    while(n > 0):
        digit = n % 10
        if(flag):
            first += digit
        else:
            second += digit
        if(flag):
            flag = False
        else:
            flag = True
        n = int(n/10)
    if(first-second == 0):
        return True
    return False
 
 
# driver code
n = 1243
if(isDiff0(n)):
    print("Yes")
else:
    print("No")


Output

Yes

Time Complexity: O(n), where n is the number of digits in the input number.
Auxiliary Space: O(1)

Please refer complete article on Difference between sums of odd and even digits for more details!


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads