Take a Number And Sum Its Digits Raised To The Consecutive Powers And ....¡Eureka!!

The number 89 is the first integer with more than one digit that fulfills the property partially introduced in the title of this kata. What's the use of saying "Eureka"? Because this sum gives the same number.

In effect: 89 = 8^1 + 9^2

The next number in having this property is 135.

See this property again: 135 = 1^1 + 3^2 + 5^3

We need a function to collect these numbers, that may receive two integers a, b that defines the range [a, b] (inclusive) and outputs a list of the sorted numbers in the range that fulfills the property described above.

Let's see some cases:

sum_dig_pow(1, 10) == [1, 2, 3, 4, 5, 6, 7, 8, 9]

sum_dig_pow(1, 100) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 89]

If there are no numbers of this kind in the range [a, b] the function should output an empty list.

sum_dig_pow(90, 100) == []

Good Solution1:

import java.util.List;
import java.util.stream.*;


class SumDigPower {
    
    public static List<Long> sumDigPow(long a, long b) {
        return LongStream.rangeClosed(a, b)
          .filter(i -> isValid(i))
          .boxed()
          .collect(Collectors.toList());
    }
    
    private static boolean isValid(long x){
      String value = Long.toString(x);
      return IntStream.range(0, value.length())
         .mapToDouble(i -> Math.pow(Character
                        .getNumericValue(value.charAt(i)), i + 1))
         .sum() == x;
    }
}

Good Solution2:

import java.util.*;

class SumDigPower {
    
    public static List<Long> sumDigPow(final long a, final long b) {
      final List<Long> ret = new ArrayList<>();
      for (long k = a; k <= b; k++) {
        long v = 0;
        int exp = 1;
        for (char c : (""+k).toCharArray()) { 
          v += Math.pow(c - '0', exp++);
          if (v > k) break;
        }
        if (v == k) ret.add(k);
      }
      return ret;
    }
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。