简体   繁体   中英

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 -

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

Presuming those are ints, you can use division and modulus by the base (10):

81 / 10 = 8
81 % 10 = 1

For the second example, you'd want to use a while (X >= 10) loop.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM