Persistent Bugger

Persistent Bugger

توضیح:

تابعی بنویسید که یک پارامتر مثبت از ورودی بگیرد (num) و اعداد آنرا ضرب کنید و تعداد مراحل را برگرداند. به این صورت که شما باید تا زمانی که یک عدد یک رقمی بدست بیاید مراحل ضرب اعداد درون یک عدد را ادامه دهید.

Description :

Write a function, persistence, that takes in a positive parameter num and returns its multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.

For example:

 persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
                      // and 4 has only one digit
                 
 persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126,
                       // 1*2*6 = 12, and finally 1*2 = 2
                  
 persistence(4) == 0 // because 4 is already a one-digit number

class Persist {
  public static int persistence(long n) {
    int count = 0;
    while (n >= 10) {
      int result = 1;
      String input = "" + n;
      for (char character : input.toCharArray()) {
        int num = Integer.parseInt("" + character);
        result *= num;
      }
      n = result;
      count++;
    }

    return (count);
  }
}
class Persist {
  public static int persistence(long n) {
    long m = 1, r = n;

    if (r / 10 == 0)
      return 0;

    for (r = n; r != 0; r /= 10)
      m *= r % 10;

    return persistence(m) + 1;
    
  }
}
class Persist {
  public static int persistence(long n) {
    int times = 0;
    while (n >= 10) {
      n = Long.toString(n).chars().reduce(1, (r, i) -> r * (i - '0'));
      times++;
    }
    return times;
  }
}
class Persist {
   /**
     * given a positive integer produce its multiplicative persistence
     * @param n a positive integer
     * @return the multiplicative persistence of n
     */
    public static int persistence(long n) {
        if (n < 10) {
            return 0;
        }
        return 1 + persistence(multiplyDigits(n));
    }
    /**
     * given an integer produce the product of the given integers digits.
     * example: multiplyDigits(785) = 7 * 8 * 5 = 280
     * @param n
     * @return the product of the digits that comprise n
     */
    private static long multiplyDigits(long n) {
        if (n < 10) {
            return n;
        }
        return n % 10 * multiplyDigits(n / 10);
    }
}
import java.util.Arrays;

class Persist {

    public static int persistence(long n) {
        if (n < 10) return 0;

        final long newN = Arrays.stream(String.valueOf(n).split(""))
                .mapToLong(Long::valueOf)
                .reduce(1, (acc, next) -> acc * next);

        return persistence(newN) + 1;
    }
}

دیدگاهتان را بنویسید