Codewars解题Playing with digits

题目

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

谷歌翻译:

给定一个正整数n写成abcd …(a,b,c,d
…是数字)和一个正整数p,我们想要找到一个正整数k,如果存在的话,比如数字的总和对于p的连续幂的n等于k * n。换一种说法:

是否有整数k,例如:(a ^ p + b ^(p + 1)+ c ^(p + 2)+ d ^(p + 3)+ …)= n * k
如果是这种情况,我们将返回k,如果不返回-1。

注:n,p将始终作为严格正整数给出。

我的理解

参数:给一个正整数n=abcde; 与p
abcde带表各个位上的数字

如果a^p+b^(p+1)+c^(p+2)+d^(p+3)+e^(p+4)暂且把值写为sum
如果sum%n==0;就返回sum/0;
否则返回-1;

以下为我的代码

public class DigPow {

    public static long digPow(int n, int p) {
    // your code
    //定义一个标记
    long tem = -1;
    //计算总和
    int sum = 0 ;
    //将初始值记录
    int ss = n;
    //计算最大次幂
    int p1 = p+(n+"").length()-1;
    //开始循环,每次循环n都除以10,直到除不尽
    while(n!=0){
       //得到个位上的数
      int m = n%10;
      //记录该数
      int m1 = m;
      for(int i = 0 ;i<p1-1;i++){
        //循环算出该位上应得的值
        m*=m1;
      }
      //将最大次幂递减
      p1--;
      //将算出来的值累加
      sum+=m;
      //去掉最后一位数
      n = n/10;
    }
    //判断是否符合条件
    if(sum%ss==0){
      //修改标记
      tem=sum/ss;
    }
    return tem;
    }

}

该方法以通过测验

以下为评分最高的解决方案

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

}

很高兴可以看得懂
目前的水平在6k徘徊,有时连7k的题都解决不了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值