Checking for a Doubleton Number in JavaScript

JavascriptWeb DevelopmentFront End Technology

Doubleton Number

We will call a natural number a "doubleton number" if it contains exactly two distinct digits. For example, 23, 35, 100, 12121 are doubleton numbers, and 123 and 9980 are not.

Problem

We are required to write a JavaScript function that takes in a number and return true if it is a doubleton number, false otherwise.

Example

Following is the code −

 Live Demo

const num = 121212;
const isDoubleTon = (num = 1) => {
   const str = String(num);
   const map = {};
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(!map.hasOwnProperty(el)){
         map[el] = true;
      };
   };
   const props = Object.keys(map).length;
   return props === 2;
};
console.log(isDoubleTon(num));

Output

Following is the console output −

true
raja
Published on 17-Apr-2021 10:50:29
Advertisements