1、题目:
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 and 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
2、我的解决方案
1 class DigPow { 2 3 public static long digPow(int n, int p) { 4 5 char[] charArray = String.valueOf(n).toCharArray(); 6 7 int sum = 0; 8 9 for (int i = 0; i < charArray.length; i++) { 10 char c = charArray[i]; 11 int num = Integer.parseInt(String.valueOf(c)); 12 13 sum += Math.pow(num, p+i); 14 15 } 16 17 if (sum%n==0) { 18 return sum/n; 19 } else { 20 return -1; 21 } 22 23 24 } 25 26 }
3、最佳解决方案
1 public class DigPow { 2 3 public static long digPow(int n, int p) { 4 String intString = String.valueOf(n); 5 long sum = 0; 6 for (int i = 0; i < intString.length(); ++i, ++p) 7 sum += Math.pow(Character.getNumericValue(intString.charAt(i)), p); 8 return (sum % n == 0) ? sum / n : -1; 9 } 10 11 }
4、总结
每一次看到最佳解决方案都很开心,为什么别人的代码这么精简。
sum用int在遇到大数的时候可能会溢出,所以最佳解决方案用的是Long;
这里重点记录一下Character.getNumericValue方法:getNumericValue方法返回指定的Unicode字符表示的int值