美文网首页
Persistent Bugger

Persistent Bugger

作者: Magicach | 来源:发表于2017-12-25 22:31 被阅读0次

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

    相关文章

      网友评论

          本文标题:Persistent Bugger

          本文链接:https://www.haomeiwen.com/subject/svvrgxtx.html