Table of contents
7-13 Find the three-digit narcissus number
Original title:
This question requires writing a program to output all three-digit narcissus numbers in the interval between given positive integers M and N. A three-digit daffodil number, that is, the sum of the cubes of its ones, tens, and hundreds digits is equal to the number itself.
Input format:
The input is given as two positive integers M and N in one line (100≤ M ≤ N ≤999).
Output format:
Output all three-digit narcissus numbers in the M and N intervals sequentially, one number in each line. If there is no three-digit narcissus number in this interval, there is no output.
If M or N does not meet the requirements of the question, output it Invalid Value.
.
.
Problem-solving ideas:
- Import
readline
the module and create an interface object: Firstreadline
introduce the module and usecreateInterface
methods to create an interface objectrl
. This object sets the input stream to standard input. - Read input and store: By listening to
'line'
events, store each line of input in an arraybuf
. - Parse the input and validate it: by
buf[0].split(" ").map(Number)
converting the input into an array containing two valuesarr
. Assign the first value to the variablem
and the second value to the variable respectivelyn
. At the same time, the validity of the sum ism
checkedn
. If the conditions are not met, "Invalid Value." is output and returned. - Find the number of daffodils: Create an empty array
res
. Use a loop to iterate through each numberfor
fromm
to .n
For each number, call a functionisDaffodil
to determine whether it is a narcissus number. If so, add it to the arrayres
. - Output result: If
res
the length of the array is less than 1, it means that the number of daffodils is not found in the given range and is returned directly. Otherwise, usefor...of
a loop to iterate through the arrayres
and output the number of each daffodil. - Define function
isDaffodil
: This function is used to determine whether a number is a narcissus number. Convert the number to a string and iterate over each numeric character, calculating the sum of its cubes. Returns if the sum of cubes is equal to the original number,true
otherwisefalse
.
.
JavaScript (node) code:
const r = require("readline");
const rl = r.createInterface({
input: process.stdin
});
let buf = [];
rl.on('line', (input) => buf.push(input));
rl.on('close', () => {
let arr = buf[0].split(" ").map(Number)
let m = arr[0]
let n = arr[1]
if (!(100 <= m && m <= n && n <= 999)) {
console.log("Invalid Value.")
return
}
let res = []
for (let i = m; i <= n; i++) {
if (isDaffodil(i)) {
res.push(i)
}
}
if (res.length < 1) {
return
} else {
for (let i of res) {
console.log(i);
}
}
});
function isDaffodil(num) {
let str = "" + num
let sum = 0
for (let i of str) {
sum += parseInt(i) ** 3
}
return num == sum
}
.