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
Checking for a Doubleton Number in JavaScript
A "doubleton number" is a natural number that contains exactly two distinct digits. For example, 23, 35, 100, and 12121 are doubleton numbers because they each use only two different digits. Numbers like 123 (three digits) and 9980 (three digits: 9, 8, 0) are not doubleton numbers.
Problem Statement
We need to write a JavaScript function that takes a number and returns true if it's a doubleton number, false otherwise.
Solution
The approach is to convert the number to a string, track unique digits using an object, and check if exactly two distinct digits exist.
const num = 121212;
const isDoubleTon = (num = 1) => {
const str = String(num);
const map = {};
// Count unique digits
for(let i = 0; i < str.length; i++){
const el = str[i];
if(!map.hasOwnProperty(el)){
map[el] = true;
}
}
// Check if exactly 2 distinct digits
const props = Object.keys(map).length;
return props === 2;
};
console.log(isDoubleTon(num));
true
How It Works
The function converts the number to a string and iterates through each character (digit). It uses an object as a map to track which digits have been seen. Finally, it counts the number of unique digits and returns true only if exactly two distinct digits are found.
Additional Examples
// Test various cases
console.log("Testing doubleton numbers:");
console.log(isDoubleTon(23)); // true - digits: 2, 3
console.log(isDoubleTon(100)); // true - digits: 1, 0
console.log(isDoubleTon(12121)); // true - digits: 1, 2
console.log("Testing non-doubleton numbers:");
console.log(isDoubleTon(123)); // false - digits: 1, 2, 3
console.log(isDoubleTon(9980)); // false - digits: 9, 8, 0
console.log(isDoubleTon(5)); // false - only one digit
console.log(isDoubleTon(1234)); // false - four digits
Testing doubleton numbers: true true true Testing non-doubleton numbers: false false false false
Conclusion
A doubleton number contains exactly two distinct digits. The solution uses string conversion and object mapping to efficiently count unique digits and verify the doubleton condition.
