如何拆开一个数字并将其数字相乘?

how to take apart a number and multiply its digits?

嗨,我正在使用代码块,我是个新手, 我想拆开一个数字并乘以它的数字 如果 number > 9 那么我想再次拆开数字并将它们相乘, 示例:如果我有数字 126,那么新数字将是 1*2*6 = 12 但是 12 > 9 然后新数字再次是 1*2 = 2,2 不是 >9 然后退出循环 谢谢

请试试这个程序:

public class B {

    public static void main(String[] args) {

        String number = "126";
        int c = 1;
        for (int j =  number.length() ; j >=0; j--) {
        int v = j;
            for (int i = 0; i < v; i++) {
                String s = ""+number.charAt(i);
                c = c*  Integer.parseInt(s.trim());
            }

            System.out.println("result is : "+c);    
            c = 1;
        }        
}
}

您需要使用一个函数来计算您输入的数字的每一位,然后迭代直到计算出一个零。这样的事情会起作用,然后 return switch 语句的其余部分:

quotient = number / 10; 
remainder = number % 10; 
switch(remainder)
{
    case 1:
        return 1
        break;
}

您可以创建一个方法来查找字符串中的数字字符,如下所示:

public static int Match(String pattern, String word) {
    int abc = 1;
    Matcher m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(word);
    while (m.find()) {

        abc *= Integer.parseInt(m.group());
        System.out.println("val of abc when (m=" + m.group() + ") - " + abc);

    }
    System.out.println("*************************");
    return abc;
}

然后你可以在你的主要方法中检查给定的字符串,直到你得到所需的数字:

    String word = "126 Florida Beach";
    String pattern = "\d";

    int abc = 1;
    do {
        System.out.println("word at  - " + word);
        System.out.println("abc at - " + abc);
        abc = Match(pattern, word);
        word = String.valueOf(abc);

    } while (abc > 9);
    System.out.println("Required Value - " + abc);

C 中的简单解决方案:

int muldigits(unsigned int n) {
    while (n > 9) {
        unsigned int m = n;
        for (n = 1; m; n *= m % 10, m /= 10);
    }
    return n;
}