Persistent Bugger

2017-12-25  本文已影响0人  Magicach

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 39 = 27, 27 = 14, 1*4=4
// and 4 has only one digit

persistence(999) == 4 // because 999 = 729, 729 = 126,
// 126 = 12, and finally 1*2 = 2

persistence(4) == 0 // because 4 is already a one-digit number

Good Solution 1:

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

Good Solution 2:

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;
  }
}
上一篇下一篇

猜你喜欢

热点阅读