gpt4 book ai didi

javascript armstrong number 测试用例错误

转载 作者:行者123 更新时间:2023-11-29 18:44:37 26 4
gpt4 key购买 nike

我要解决的问题是:

Write a javascript program which returns true when a given number is Armstrong number and false otherwise. Any n digit number is armstrong number if sum of nth power of each digit equals to the number itself. Example: 153 is a 3 digit armstrong number because sum of 3rd power of each digit equals to 153 (153 = 1*1*1 + 5*5*5 + 3*3*3).

Hint: Use Math.pow(i,n) to calculate nth power of i. Use parseInt(i) to get integer value of i. Your output code should be in the format console.log("Result is ", variableName)

我的代码是:

var num = prompt("Enter a number to check Armstrong");
var t = "Armstrong";
var f = "Not Armstrong";

function armst(x) {
var a = x, b, sum = 0;
while (a > 0) {
b = a % 10;
sum += (b * b * b);
a = parseInt(a / 10);
}

if (sum === x) {
return t;
} else {
return f;
}
}

var output = armst(num);
console.log("Result is : ", output);

当我在类(class)网站上运行这段代码时,它给出了正确的输出,但没有通过编译器的所有测试用例。

我错过了什么吗?哪些地方可以改进?

最佳答案

为了获得 narcissistic number/Armstrong number,需要将数字的长度作为字符串作为n取幂求和。

只是个人的话,因为规范,我会采取Math.floor ,因为您已经有了一个数字,而不是 parseInt .

function armst(x) {
var value = parseInt(x, 10),
rest = value,
digit,
sum = 0,
n = x.toString().length; // add toString, if a number is entered

while (rest) {
digit = rest % 10;
rest = Math.floor(rest / 10);
sum += Math.pow(digit, n); // use it here
}

return sum === value
? "Armstrong"
: "Not Armstrong";
}


var num = prompt("Enter a number to check Armstrong"), // try with 54748
output = armst(num);

console.log("Result is: ", output);

关于javascript armstrong number 测试用例错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54801762/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com