#Sum of the digits

18 messages · Page 1 of 1 (latest)

storm meteor
#

I am still a beginner learner in java. While practising, i found this problem:

Write a java program that takes a number between 1 to 1000 as input and outputs the sum of all digits of the number. You cannot use these:

1. String methods
2. Loop
3. Array

What I can understand that I have to use mathematical expressions to solve this. But how am I supposed to do it?

naive driftBOT
#

This post has been reserved for your question.

Hey @storm meteor! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

graceful path
#

you can n % 10 to get the last digit of the integer, then n /= 10 to cut off the last digit
some use of that is probably the intended solution

storm meteor
#

but i cannot use loop to determine the length of the number so i can iterate the same thing...

graceful path
#

yeah idk about that part

frail topaz
#
    System.out.print("Enter a number from 0 to 1000:\n>> ");
    int number = new Scanner(System.in).nextInt();

    if (number / 10 == 0) {
      System.out.println(number);
      System.exit(0);
    }

    int sum = 0;
    sum += number % 10;
    number /= 10;

    if (number / 10 == 0) {
      System.out.println(sum + number);
      System.exit(0);
    }

    sum += number % 10;
    number /= 10;

    if (number / 10 == 0) {
      System.out.println(sum + number);
      System.exit(0);
    }

    sum += number % 10;
    number /= 10;

    if (number / 10 == 0) {
      System.out.println(sum + number);
      System.exit(0);
    }
#

There's probably a more elegant way using mod to find the length and then doing a calculation based on that

safe saffron
#

I mean, adding zero to a number doesn't change that number. Exiting the program isn't all that important

#

So yeah, check the number is indeed between 0 and 1000, then compensate for the absence of loops by doing the same thing 4 times

#

You could also solve it recursively

wicked grotto
#

that just sounds like a stupid question

#

one way to solve it (with a loop though): ```java
int n = 999;
int nDigits = (int) (Math.log10(n)+1);
int sum = 0;
for(int i = 0; i < nDigits; i++) {
sum += (int) (n/Math.pow(10, i)) % 10;
}

#

log10(n)+1 gets the number of digits from n, that's what that is

#

the rest is pretty self explanatory

safe saffron
#

Or you could opt out of caring about the number of digits

wicked grotto