Sum all digits of a number and show the digits separately in Java

ε祈祈猫儿з 提交于 2021-02-04 18:09:12

问题


I've been using this site quite a lot but I've never really wrote anything. Today, I've stumbled upon a problem which solution I can't seem to find.

The problem is that, I have an int variable with an unknown number of digits. It is asked of me to sum all of those digits and then have it printed/shown_as_a_message with all those digit separated.

For example, the user enters the number "12345678" and in the end I need to have a message saying "The numbers 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 = 36". I know how to separate and sum all of those numbers, but I don't know how to save each number and then have it shown, because not only do I not know the right amount of digits, but I don't know their values either.

Usually that wouldn't be hard to do, but here comes the tricky part for me, since we haven't learned things like arrays, strings, indexes, etc., we're not allowed to use them. So, I'm supposed to do it with the simplest type of code possible.

So far, I've got the following:

import java.util.Scanner;
public class Numbers {
    public static void main(String[] args) {
        int number, result;
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number:");
        number = sc.nextInt();
        result = 0;
        while (number > 0){
            result = result + (number % 10);
            number = number / 10;
        }
        System.out.println("This is where the message would go.");
    }
}

回答1:


static final Scanner input = new Scanner(System.in);

public static void main(String[] args) {
    int number, result;
    System.out.println("Enter number:");
    number = input.nextInt();
    result = 0;
    System.out.print("The numbers: ");

    //Reverses the number
    int reversedNum = 0;
    while (number != 0) {
        reversedNum = reversedNum * 10 + number % 10;
        number = number / 10;
    }

    //Iterates over the number and prints it out
    while (reversedNum > 0) {
        System.out.print((reversedNum % 10));

        result = result + (reversedNum % 10);
        reversedNum = reversedNum / 10;

        if (reversedNum > 0) {
            System.out.print(" + ");
        }
    }
    System.out.println(" = " + result);
}

This works to print out all the numbers in the correct order without using arrays and strings.

Example:

Enter number:
12345
The numbers: 1 + 2 + 3 + 4 + 5 = 15
BUILD SUCCESSFUL (total time: 5 seconds)



回答2:


Perhaps something like this where you aren't using any sort of container. Simply concatenate to the string each of time you find a new number.

    int number, result;
    String finalOutput = "";
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number:");
    number = sc.nextInt();
    result = 0;

    while (number > 0){
        result = result + (number % 10);

        finalOutput += (number % 10);

        number = number / 10;
        if(number > 0)
        {
            finalOutput += " + ";
        }else{
            finalOutput += " = ";
        }
    }
    System.out.println("The numbers " + finalOutput + result);



回答3:


You want to print out these numbers as you are looping. Ex:

while (number > 0){
     System.out.print( (number % 10) + " + " );
     result = result + (number % 10);
     number = number / 10;
}

You still have the task of getting your output formatted correctly.




回答4:


I had a similar task a year ago. Basically what I did is to turn the inputted integer into a String using String.valueOf(int) (Integer.toString(int) works too) then I turn every char in that String back to integers and adds them to the sum.

Scanner sc = new Scanner(System.in);

int sum= 0;

System.out.println("Number?");
int num = sc.nextInt();
sc.close();

String countNum = String.valueOf(num);

for(int i = 0; i < countNum.length(); i++) {
   int j = Character.digit(countNum.charAt(i), 10);
   sum += j;
}
System.out.println("The sum is: " + sum);



回答5:


If you're ok using regular expressions, and simply want to insert a plus sign surrounded by spaces between all the digits, you can use the replaceAll() method:

"12345678".replaceAll("\\B", " + ") // returns "1 + 2 + 3 + 4 + 5 + 6 + 7 + 8"

\\B is the regular expression for matching the empty positions between characters that are not word breaks (\\b would be positions that are word breaks). Since the input is a single "word" consisting of all digits, the beginning and end of the value are word breaks, and the positions between digits are not word breaks.

replaceAll() then replaces all those empty spaces between digits with " + ", and you get exactly what you wanted in a simple expression.




回答6:


You can do it recursively:

int number,result;
Scanner sc = new Scanner(System.in);
System.out.println("Enter number:");
number = sc.nextInt();
//sum to the result and print last digit and the result
int last = number%10;
result = reverse(number/10);
System.out.print(last + " = "+ (result + last));

Recursive method, print the string and compute the sum (except last digit):

private static int reverse(int number) {
    if(number>0){
        int p = number % 10 + reverse(number/10);
        System.out.print(number % 10 + " + ");
        return p;
    }
    return 0;
}



回答7:


(Posted on behalf of the OP).

Solved by Luke Melaia!

Another thing that might be helpful to people Google-ing this:

Shortest solution with String -> "12345678".replaceAll("\B", " + ") ➜ 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 – Andreas

Recursive Solution by user6904265.

Thank you all for the great help. Much appreciated. <3




回答8:


With the help of Java8, you can do it by this way:

public int sumNumber(int number) {
        return String.valueOf(number).chars().map(Character::getNumericValue).sum();
    }

This might help to someone.



来源:https://stackoverflow.com/questions/40665438/sum-all-digits-of-a-number-and-show-the-digits-separately-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!