Playing with digits

Some numbers have funny properties. For example:

89 --> 81 + 92 = 89 * 1

695 --> 62 + 93 + 5?= 1390 = 695 * 2

46288 --> 43 + 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 81 + 92 = 89 = 89 * 1
digPow(92, 1) should return -1 since there is no k such as 91 + 22 equals 92 * k
digPow(695, 2) should return 2 since 62 + 93 + 5?= 1390 = 695 * 2
digPow(46288, 3) should return 51 since 43 + 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;
  }
  
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容