Finding the count of total upside down numbers in a range using JavaScript

Upside Down Numbers

Upside down numbers are special numbers that remain identical when rotated 180 degrees. Only certain digits can form upside down numbers: 0, 1, 6, 8, and 9, where 6 becomes 9 and vice versa when rotated.

For example, 69 becomes 69 when rotated, and 8108 becomes 8018 (which is not the same, so it's not upside down).

Problem Statement

We need to write a JavaScript function that takes a range of two numbers and returns the count of all upside down numbers within that range.

Understanding Valid Digits

When rotated 180 degrees:

  • 0 ? 0
  • 1 ? 1
  • 6 ? 9
  • 8 ? 8
  • 9 ? 6
  • Other digits (2, 3, 4, 5, 7) cannot form upside down numbers

Solution

const range = [5, 125];

const flipNum = (number) => {
    const upsideDownDigits = [0, 1, -99, -99, -99, -99, 9, -99, 8, 6];
    let reverseNumArr = String(number)
        .split('')
        .map(val => Number(val))
        .reverse();
    
    let flipDigitsNumArr = reverseNumArr.map(val => upsideDownDigits[val]);
    
    if (flipDigitsNumArr.includes(-99)) {
        return false;
    }
    
    let flipDigitsNum = Number(
        flipDigitsNumArr.reduce((accum, curr) => accum + String(curr), '')
    );
    
    return flipDigitsNum === number;
};

const countUpsideDown = ([lowNum, highNum]) => {
    let uDNums = 0;
    for (let counter = lowNum; counter 

Output

7

How It Works

The solution uses two main functions:

  1. flipNum(number): Checks if a number is upside down by converting each digit to its rotated equivalent and comparing with the original
  2. countUpsideDown([lowNum, highNum]): Iterates through the range and counts valid upside down numbers

The upsideDownDigits array maps each digit (0-9) to its upside down equivalent, using -99 for invalid digits that cannot be rotated.

Example Verification

// Test individual numbers
console.log("Testing individual numbers:");
console.log("69 is upside down:", flipNum(69));   // true
console.log("96 is upside down:", flipNum(96));   // true  
console.log("123 is upside down:", flipNum(123)); // false

// Find upside down numbers in range [5, 125]
console.log("\nUpside down numbers in range [5, 125]:");
for (let i = 5; i 

Testing individual numbers:
69 is upside down: true
96 is upside down: true
123 is upside down: false

Upside down numbers in range [5, 125]:
6
8
9
11
16
18
19

Conclusion

This algorithm efficiently identifies upside down numbers by mapping digits to their rotated equivalents and checking for equality. The solution handles edge cases where digits cannot be rotated (2, 3, 4, 5, 7) by using sentinel values.

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

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements