java - Java:Three digit Sum - Find out all the numbers between 1 and 999 where the sum of 1st digit and 2nd digit is equal to 3rd digit
问题描述
Problem statement: Three digit sum - Find all the numbers between 1 and 999 where the sum of the 1st digit and the 2nd digit is equal to the 3rd digit.
Examples:
123 : 1+2 = 3
246 : 2+4 = 6
Java:
public class AssignmentFive {
public static void main(String[] args) {
int i=1;
int valuetwo;
int n=1;
int sum = 0;
int valuethree;
int valueone = 0;
String Numbers = "";
for (i = 1; i <= 999; i++) {
n = i;
while (n > 1) {
valueone = n % 10;/*To get the ones place digit*/
n = n / 10;
valuetwo = n % 10;/*To get the tens place digit*/
n = n / 10;
valuethree = n;/*To get the hundreds place digit*/
sum = valuethree + valuetwo;/*adding the hundreds place and
tens place*/
}
/*Checking if the ones place digit is equal to the sum and then print
the values in a string format*/
if (sum == valueone) {
Numbers = Numbers + n + " ";
System.out.println(Numbers);
}
}
}
}
I got my result :
1
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000001
100000000011
1000000000111
10000000001111
100000000011111
1000000000111111
10000000001111111
100000000011111111
1000000000111111111
Process finished with exit code 0
The result is not showing the actual result like it should be which should show values like: 123, 246 (Please refer to the problem statement above.)
Please let me know what seems to be the issue with the code and how to tweak it.
解决方案
不知道你想用那个while
循环做什么,或者你为什么要建立一个以空格分隔的数字字符串。
你的代码应该是这样的:
for (int n = 1; n <= 999; n++) {
int digit1 = // for you to write code here
int digit2 = // for you to write code here
int digit3 = // for you to write code here
if (digit1 + digit2 == digit3) {
// print n here
}
}
推荐阅读
- python - 如何在 heroku 上托管我的 discord.py 机器人?
- javascript - 变量 dans appel jquery
- database - Haskell“持久”模型:如何正确定义交叉引用?
- javascript - 为什么日期格式函数返回错误答案?
- azure - 具有条件控制的 Azure LogicApp 无法正常工作
- amazon-web-services - AWS OCSP 装订
- java - @DataJpaTest 不会读取 spring.jpa.* 属性,而 @SpringBootTest 会
- ruby-on-rails - 如何确定我的应用在达到 Twitter API 的速率限制之前还能发出多少请求?
- heroku - 试图在 Heroku 上服务 ML (pytorch) 模型,slug 太大
- .net - 使用异步正确调用匿名方法