Finding confusing number within an array in JavaScript

A number in an array is confusing if it becomes another number which is also present in the array after we rotate it by 180 degrees. When rotated, digits transform as follows: 0?0, 1?1, 6?9, 8?8, 9?6. Other digits (2, 3, 4, 5, 7) cannot be rotated to form valid numbers.

Understanding Confusing Numbers

For a number to be confusing:

  • It must contain only the digits 0, 1, 6, 8, 9
  • When rotated 180 degrees, it must form a valid number within our range
  • The rotated number must also be present in the array

Example

For num = 10, the array is [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]. The confusing numbers are:

  • 1 ? rotates to 1 (valid)
  • 6 ? rotates to 9 (valid)
  • 8 ? rotates to 8 (valid)
  • 9 ? rotates to 6 (valid)
  • 10 ? rotates to 01 = 1 (valid)
const num = 10;

const countConfusing = (num = 1) => {
    let count = 0;
    const valid = '01689';
    const rotateMap = {'0': '0', '1': '1', '6': '9', '8': '8', '9': '6'};
    
    const prepareRotation = num => {
        let res = '';
        const numArr = String(num).split('');
        
        // Check if all digits can be rotated
        if(numArr.some(el => !valid.includes(el))){
            return false;
        }
        
        // Build rotated number (reverse order for 180° rotation)
        numArr.map(el => {
            res = rotateMap[el] + res;
        });
        
        return +res;
    };
    
    for(let i = 1; i  0 && rotated 

5

How It Works

The algorithm processes each number from 1 to num:

  1. Validation: Check if all digits are rotatable (0, 1, 6, 8, 9)
  2. Rotation: Transform each digit using the rotation map
  3. Reversal: Build the result in reverse order (180° rotation effect)
  4. Range Check: Verify the rotated number is within [1, num]

Testing with Different Values

console.log("Testing different ranges:");
console.log("num = 5:", countConfusing(5));   // Should be 2 (1, 8 if 8 

Testing different ranges:
num = 5: 1
num = 20: 6
num = 100: 19

Conclusion

Confusing numbers are those that remain valid when rotated 180 degrees and stay within the given range. The solution efficiently checks each number by validating its digits and computing the rotation transformation.

Updated on: 2026-03-15T23:19:00+05:30

300 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements