Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Difference between sums of odd and even digits.
Given a number n, check whether the difference between the sum of digits at odd positions and the sum of digits at even positions is zero. Positions are indexed starting from 0 (rightmost digit).
Key Insight
A number is divisible by 11 if and only if the alternating sum of its digits (difference between sum of digits at odd and even positions) is 0 or divisible by 11. So a simple n % 11 == 0 check can determine if the difference is zero.
Worked Example
For n = 1212112 −
Digits: 1 2 1 2 1 1 2 Position: 6 5 4 3 2 1 0 Sum of odd positions (5,3,1) = 2 + 2 + 1 = 5 Sum of even positions (6,4,2,0) = 1 + 1 + 1 + 2 = 5 Difference = 5 - 5 = 0 ? Yes
Java Implementation
The following program checks if the difference is zero using the divisibility by 11 trick ?
class JavaTester {
public static int difference(int n) {
return (n % 11);
}
public static void main(String args[]) {
int n = 1212112;
System.out.println("Number: " + n);
System.out.println(difference(n) == 0 ? "Yes" : "No");
n = 12121121;
System.out.println("Number: " + n);
System.out.println(difference(n) == 0 ? "Yes" : "No");
}
}
The output of the above code is ?
Number: 1212112 Yes Number: 12121121 No
Conclusion
The difference between sums of odd-positioned and even-positioned digits is zero when the number is divisible by 11. This provides an efficient O(1) solution using the modulo operator instead of extracting individual digits.
