← 输入框|github.com|刷新
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
28 changes: 28 additions & 0 deletions Maths/BounceNumber.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @function isBounceNumber
* @description A bounce number is a number whose digits are neither
* entirely increasing nor entirely decreasing from left to right.
* For example, 155349 is a bounce number.
* @param {number} n - A positive integer
* @returns {boolean} - True if n is a bounce number, false otherwise
* @see https://projecteuler.net/problem=112
* @example isBounceNumber(155349) => true
* @example isBounceNumber(1234) => false
* @example isBounceNumber(9876) => false
*/
const isBounceNumber = (n) => {
if (!Number.isInteger(n) || n < 1) {
throw new TypeError('Input must be a positive integer')
}
const digits = String(n).split('').map(Number)
if (digits.length === 1) return false
let increasing = false
let decreasing = false
for (let i = 1; i < digits.length; i++) {
if (digits[i] > digits[i - 1]) increasing = true
if (digits[i] < digits[i - 1]) decreasing = true
}
return increasing && decreasing
}

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

describe('isBounceNumber', () => {
test('155349 is a bounce number', () => {
expect(isBounceNumber(155349)).toBe(true)
})

test('121 is a bounce number', () => {
expect(isBounceNumber(121)).toBe(true)
})

test('1234 is NOT a bounce number (increasing)', () => {
expect(isBounceNumber(1234)).toBe(false)
})

test('9876 is NOT a bounce number (decreasing)', () => {
expect(isBounceNumber(9876)).toBe(false)
})

test('1111 is NOT a bounce number (all same)', () => {
expect(isBounceNumber(1111)).toBe(false)
})

test('single digit is NOT a bounce number', () => {
expect(isBounceNumber(5)).toBe(false)
})

test('132 is a bounce number', () => {
expect(isBounceNumber(132)).toBe(true)
})

test('321 is NOT a bounce number (decreasing)', () => {
expect(isBounceNumber(321)).toBe(false)
})

test('123454321 is a bounce number', () => {
expect(isBounceNumber(123454321)).toBe(true)
})

test('throws TypeError for zero', () => {
expect(() => isBounceNumber(0)).toThrow(TypeError)
})

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

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