Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions Maths/StrobogrammaticNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/**
* @function isStrobogrammaticNumber
* @description A strobogrammatic number is a number whose numeral is
* rotationally symmetric, so it appears the same when rotated 180 degrees.
* Valid strobogrammatic digit pairs: 0↔0, 1↔1, 6↔9, 8↔8, 9↔6.
* @param {number} n - A positive integer
* @returns {boolean} - True if n is a strobogrammatic number, false otherwise
* @see https://en.wikipedia.org/wiki/Strobogrammatic_number
* @example isStrobogrammaticNumber(69) => true
* @example isStrobogrammaticNumber(818) => true
* @example isStrobogrammaticNumber(123) => false
*/
const isStrobogrammaticNumber = (n) => {
if (!Number.isInteger(n) || n < 0) {
throw new TypeError('Input must be a non-negative integer')
}
const map = { 0: '0', 1: '1', 6: '9', 8: '8', 9: '6' }
const str = String(n)
let left = 0
let right = str.length - 1
while (left <= right) {
if (map[str[left]] !== str[right]) return false
left++
right--
}
return true
}

export { isStrobogrammaticNumber }
51 changes: 51 additions & 0 deletions Maths/test/StrobogrammaticNumber.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { isStrobogrammaticNumber } from '../StrobogrammaticNumber.js'

describe('isStrobogrammaticNumber', () => {
test('0 is strobogrammatic', () => {
expect(isStrobogrammaticNumber(0)).toBe(true)
})

test('1 is strobogrammatic', () => {
expect(isStrobogrammaticNumber(1)).toBe(true)
})

test('8 is strobogrammatic', () => {
expect(isStrobogrammaticNumber(8)).toBe(true)
})

test('69 is strobogrammatic', () => {
expect(isStrobogrammaticNumber(69)).toBe(true)
})

test('96 is strobogrammatic', () => {
expect(isStrobogrammaticNumber(96)).toBe(true)
})

test('818 is strobogrammatic', () => {
expect(isStrobogrammaticNumber(818)).toBe(true)
})

test('1001 is strobogrammatic', () => {
expect(isStrobogrammaticNumber(1001)).toBe(true)
})

test('123 is NOT strobogrammatic', () => {
expect(isStrobogrammaticNumber(123)).toBe(false)
})

test('2 is NOT strobogrammatic', () => {
expect(isStrobogrammaticNumber(2)).toBe(false)
})

test('100 is NOT strobogrammatic', () => {
expect(isStrobogrammaticNumber(100)).toBe(false)
})

test('throws TypeError for negative input', () => {
expect(() => isStrobogrammaticNumber(-69)).toThrow(TypeError)
})

test('throws TypeError for float input', () => {
expect(() => isStrobogrammaticNumber(6.9)).toThrow(TypeError)
})
})
Loading