英文:
I have trouble finding all the 3-digit numbers whose sum of digits equal my target number
问题
下面是代码部分的翻译:
let input = [
'300',
'400',
'4'
];
let print = this.print || console.log;
let gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
var remainder, sumOfDigits = 0;
var n1 = +gets();
var n2 = +gets();
var n3 = +gets();
for (i = n1; i <= n2; i++) {
while (i) {
remainder = i % 10;
sumOfDigits = sumOfDigits + remainder;
i = Math.floor(n / 10);
if (sumOfDigits = n3) {
print(i);
}
}
}
注意:代码中存在一个错误,if 语句应该是 if (sumOfDigits == n3)
而不是 if (sumOfDigits = n3)
,等号应该是双等号用于比较相等,而不是单等号用于赋值。
英文:
Input
The input consists of exactly 3 lines
(x - interval start (inclusive))
(y - interval end (inclusive))
(t - target sum)
(example Input) =
'300',
'400',
'4'
(What it should Output) =
'301',
'310',
'400'
let input = [
'300',
'400',
'4'
];
let print = this.print || console.log;
let gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
var remainder, sumOfDigits = 0;
var n1 = +gets();
var n2 = +gets();
var n3 = +gets();
for (i=n1;i<=n2;i++){
while(i)
{
remainder = i % 10;
sumOfDigits = sumOfDigits + remainder;
i = Math.floor(n/10);
if(sumOfDigits=n3){
print(i);
}
}
}
答案1
得分: 0
在提供的代码中存在问题,比如在循环中使用了“"n"”而不是“"i"”,以及在if语句中使用了赋值“="”而不是比较“=="”。
let input = ['300','400','4'];
let gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
let n1 = +gets();
let n2 = +gets();
let n3 = +gets();
for (let i = n1; i <= n2; i++) {
let remainder, sumOfDigits = 0;
let num = i;
while (num) {
remainder = num % 10;
sumOfDigits += remainder;
num = Math.floor(num / 10);
}
if (sumOfDigits === n3) {
console.log(i);
}
}
希望这对你有所帮助。
英文:
There are issues in the code you provided, such as using "n" instead of "i" in the loop and using an assignment "=" instead of a comparison "==" in the if statement.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let input = ['300','400','4'];
let gets = this.gets || ((arr, index) => () => arr[index++])(input, 0);
let n1 = +gets();
let n2 = +gets();
let n3 = +gets();
for (let i = n1; i <= n2; i++) {
let remainder, sumOfDigits = 0;
let num = i;
while (num) {
remainder = num % 10;
sumOfDigits += remainder;
num = Math.floor(num / 10);
}
if (sumOfDigits === n3) {
console.log(i);
}
}
<!-- end snippet -->
Hope this will help to you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论