Home > Mobile >  Function to check if a given number do contain les than two different digits
Function to check if a given number do contain les than two different digits

Time:03-26

I want to implement a function to check if a given number do contain les than two different digits, that are called duodigits

For example :

12 , 110 , -33333 : are all duodigits , since they have no more than two different digits 102 : is not a duodigit since his digits ; 1 and 0 and 2 are three different digits

How may I implement a method , which may iterate and check if it's a duodgits or not and return true or false as result

CodePudding user response:

Here is how I would do it:

/**
 * Checks if a number is a duodigit.
 * @param {number} num 
 * @returns {boolean}
 */
function isDuodigit(num) {
  return new Set(Math.abs(num).toString()).size <= 2;
}

CodePudding user response:

If you want to do it without a set or string conversion.

function isDuoDigit(num){
    num = Math.abs(num);
    let first = '', second = '';
      while (num > 0) {
        let digit = num % 10;
        if(first === '')
          first = digit
        else if(second === '')
          second = digit
        else if(first !== digit && second !== digit)
           return false;
        num = Math.trunc(num / 10);
      }
  return true;
}
  • Related