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

Shruthi Ravishankar :

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.

Andreas :

Don't know what you're trying to do with that while loop, or why you are building up a space-separated string of numbers.

Your code should be something like:

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
   }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=400696&siteId=1