简体   繁体   English

如何通过在Java中执行每个数字的乘积从一组数字中查找一位数字

[英]How to find single digit from a set of number by doing product of each numbers in java

I have a number like 99 now I need to get a single digit number like - 我有一个数字,例如99,现在我需要获得一个数字,例如-

9*9 = 81
8*1 = 8

ex2:
3456 3*4*5*6
360 3*6*0

What will be the efficient way to get the output beside change the number to character/string then multiply with each adjacent . 除了将数字更改为字符串/字符串,然后与每个相邻的字符串相乘,获得输出的有效方法是什么。

Let me make the problem little more complex , what if I want to get the number of steps required to make the N to a single digit , then recursion may loose the steps and need to be done in a single method only 让我让这个问题稍微复杂一点,如果我想获得使N变为一位数字所需的步骤数,那么递归可能会使步骤松散,并且仅需要用一种方法完成

Presuming those are ints, you can use division and modulus by the base (10): 假设这些是整数,则可以使用以底数(10)为单位的除法和模数:

81 / 10 = 8
81 % 10 = 1

For the second example, you'd want to use a while (X >= 10) loop. 对于第二个示例,您想使用while (X >= 10)循环。

This recursive function should do it... 这个递归函数应该做到这一点...

int packDown( int num ) {
  if( num < 10 ) return num ;
  int pack = 1 ;
  while( num > 0 ) {
    pack *= num % 10 ;
    num /= 10 ;
  }
  return packDown( pack ) ;
}
public static int digitMultiply(int number) {
    int answer = 1;
    while (number > 0) {
        answer=answer*(number % 10);
        number = number / 10;
    }
    return answer;
}

hope it helps!! 希望能帮助到你!! simple algorithm to multiply.. 简单的乘法运算法则

The following single recursive method should work also: 以下单个递归方法也应起作用:

int multDig(int number){
  if(number >= 10)
    return multDig((number%10) * multDig(number/10));
  else
    return number;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从Java Stream获取以该数字开头的每个数字的数字? - How to get for each digit number of numbers that start with that digit from Java Stream? 查找由两个3位数字的乘积组成的最大回文。 (Java) - Find the largest palindrome made from the product of two 3-digit numbers. (Java) 找到由两个3位数字的乘积制成的最大回文 - Find the largest palindrome made from the product of two 3-digit numbers 如何在Java中读取数字的每个数字 - How to read each individual digit of a number in Java Java正则表达式从字符串中提取“仅”一位数字 - java regex to extract 'only' the single digit numbers from a string java中将每个数字与整数分开的递归数 - recursive number that separates each digit from integer number in java Java,如何从一个数字中删除一位数字(以便对其余数字进行计算)? - Java, How do I drop one single digit from a number (In order to perform a calculation on the rest of the number)? 求数组中回文数的个位数和 - To find the single digit sum of palindrome numbers in array 从用户那里获取 6 位数字输入并将每个数字存储在 Java 中的单个数组中 - Take 6 digit input from user and store each digit in a single array in Java 如何求java中一个数的乘积和位数和? - How to find the product and sum of digits of a number in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM