[英]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.