【问题标题】:how to take apart a number and multiply its digits? [closed]如何分解一个数字并乘以它的数字? [关闭]
【发布时间】:2015-11-21 11:53:12
【问题描述】:

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

【问题讨论】:

  • 整数; int newnum = 1; printf("请输入号码\n"); scanf("%d",&num); while (newnum > 9){ 数字 = num %10;新数字 *= 数字;数/= 10; @MadushanPerera 我知道我一直将所有旧数字的所有结果添加到新数字中:\

标签: java c loops while-loop numbers


【解决方案1】:

请试试这个程序:

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

【讨论】:

    【解决方案2】:

    一个简单的C语言解决方案:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

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

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

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

            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);
        

        【讨论】:

        • @down-voter 我可以知道原因吗???
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-11-22
        • 1970-01-01
        • 1970-01-01
        • 2017-07-09
        • 1970-01-01
        • 2013-05-11
        • 1970-01-01
        相关资源
        最近更新 更多