zoukankan      html  css  js  c++  java
  • Codewars题记 :Some numbers have funny properties.

    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值

  • 相关阅读:
    C语言 strcat
    C语言 strncpy
    C语言 strcpy
    C语言 main
    可显示Android设备选择列表,并进入指定Android设备Console的Shell脚本
    Android系统如何录制屏幕(录制成mp4格式)
    据说有99%的人都会做错的面试题
    一道淘汰85%面试者的百度开发者面试题
    用Android模拟器也可以开发和测试NFC应用
    一道腾讯面试题的思考:到底谁会赢?
  • 原文地址:https://www.cnblogs.com/RivenLw/p/11272368.html
Copyright © 2011-2022 走看看