algorithm/codewars
[6kyu] playing with digits
안준범
2018. 1. 28. 19:08
문제설명
Description:
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.
Examples :
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
나의 풀이
function digPow(n, p){
var sum = 0;
var len = String(n).length;
var v = n;
while(0 < len){
var singleDig = Math.floor(v/(Math.pow(10,len-1)));
sum += Math.pow(singleDig,p);
v = v - (singleDig*(Math.pow(10,len-1)));
p++;
len--;
}
return !(sum%n) ? sum/n : -1;
}
다른사람의 풀이
function digPow(n, p) {
var x = String(n).split("").reduce((s, d, i) => s + Math.pow(d, p + i), 0)
return x % n ? -1 : x / n
}
--------------------------------------------------------------------
function digPow(n, p){
var ans = (''+n).split('')
.map(function(d,i){return Math.pow(+d,i+p) })
.reduce(function(s,v){return s+v}) / n
return ans%1 ? -1 : ans
}
느낀점
다른사람이 푼 두 개의 인상깊은 풀이가 있었다. ES6문법은 잘 몰라서 첫번째 풀이는 이해가 시간이 걸렸지만, 두번째 풀이는 다 아는건데 생각지 못해서 아쉽다.많이 멀었구나 싶다.. 참 적절하게 연결이 잘 된 풀이인듯하다. 지금 내 풀이를 보면 당시에 왜 저렇게 풀었나 싶다. 그렇게 많이 써본 split 메서드인데 왜 안썼나.. 생각이 든다.