美文网首页
Playing with digits

Playing with digits

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

Some numbers have funny properties. For example:

89 --> 8¹ + 9² = 89 * 1

695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2

46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p we want to find a positive integer k, if it exists, such as the sum of the digits of n taken to the successive powers of p is equal to k * n. In other words:

Is there an integer k such as : (a ^ p + b ^ (p+1) + c ^(p+2) + d ^ (p+3) + ...) = n * k

If it is the case we will return k, if not return -1.

Note: n, p will always be given as strictly positive integers.

digPow(89, 1) should return 1 since 8¹ + 9² = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 9¹ + 2² equals 92 * k
digPow(695, 2) should return 2 since 6² + 9³ + 5⁴= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51

Good Solution1:

public class DigPow {
  
  public static long digPow(int n, int p) {
    String intString = String.valueOf(n);
    long sum = 0;
    for (int i = 0; i < intString.length(); ++i, ++p)
      sum += Math.pow(Character.getNumericValue(intString.charAt(i)), p);
    return (sum % n == 0) ? sum / n : -1;
  }
  
}

Good Solution2:

class DigPow {
  
  public static long digPow(int n, int p) {
    long s = 0;
    String nstr = String.valueOf(n);
    for (int i = 0; i < nstr.length(); i++) {
      s += (long)Math.pow((int)(nstr.charAt(i) -'0'), p+i);
    }
    if (s % n == 0) 
      return s / n;
    else return -1;
  }
  
}

相关文章

  • Playing with digits

    Some numbers have funny properties. For example: Given a ...

  • dict

    dict 遍历 digits.keys() digits.values() digits.items()

  • 计算阶乘结果中的数字个数

    翻译来源 Count digits in a factorial | Set 1 Count digits in ...

  • Playing With Groupcache

    Playing With Groupcache This week,@bradfitz(of memcached ...

  • Playing Sounds

    通过调用pygame.mixer.Sound() 构造函数来创建一个pygame.mixer.Sound对象(我们...

  • playing with fire

    [JENNIE] 屋里 奥m慢 没一累给 吗累搜 恩姐那 那m加 就西吗啦够 撒狼恩 吗起 不r讲男 噶他搜 她起...

  • Playing Truant

    今天我翘了一天学校回到家,老爸翘了一天班飞回北京,我们一起去爬香山。天气好到像是回到了小时候。回到家,洗过澡,困了...

  • Playing Badminton

    I cooked the lunch at 11:30,a little earlier than usual. ...

  • 《Playing Love》

    你的孤独已深入骨髓,你的自由已沉入海水。

  • Leetcode PHP题解--D71 788. Rotated

    D71 788. Rotated Digits 题目链接 788. Rotated Digits 题目分析 当一个...

网友评论

      本文标题:Playing with digits

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