Simple Fun #290: Sum Of Threes ( 6 kyu )

문제

Task

Given a number n, return a string representing it as a sum of distinct powers of three, or return “Impossible” if that’s not possible to achieve.

Input/Output

[input] integer n

A positive integer n.

1 ≤ n ≤ 10^16.

[output] a string

A string representing the sum of powers of three which adds up to n, or “Impossible” if there is no solution. If the solution does exist, it should be return as “3a1+3a2+ … +3^an”, where ai for 0 ≤ i ≤ n represents the corresponding exponent of the term. The terms in the string should also be sorted in descending order, meaning that higher powers should appear before the lower ones in the string (“30+31” is incorrect, whereas “31+30” is correct).

인자로 주어진 수가 3의 제곱수의 합으로 나타내질 수 있는지를 판별하는 문제

풀이

function sumOfThrees(n) {
  let str = n.toString(3), result = '';
  if ( !(str.indexOf('2') === -1) ) return 'Impossible';
  for ( let i = 0; i < str.length; i++ ) {
    if ( str[i] === '1' ) {
      result += `3^${str.length-1-i}+`
    }
  }
  return result.slice(0, result.length-1);
}

3의 제곱수임을 판별하기 위해 3진법으로 변환 후에, 2가 있으면 impossible을 리턴하고 else 경우에 각 진법의 자릿수만큼 곱한 스트링을 결과값에 더해 리턴

다른 사람의 풀이

function sumOfThrees(n) {
  var t = n.toString(3)
  return /2/.test(t) ? "Impossible"  : 
  [...t].reverse().reduce((a,v,k)=>
    (v==1) ? a.concat("3^"+k) : a, []).reverse().join('+')
}

접근은 같지만 깔끔한 풀이


'자료구조, 알고리즘 > Codewars 문제' 카테고리의 다른 글

String average ( 6 kyu )  (0) 2017.12.19
Array Helper ( 6 kyu )  (0) 2017.12.19
RGB To Hex Conversion ( 5 kyu )  (0) 2017.12.11
Checking Groups ( 6 kyu )  (0) 2017.12.11
Rectangle into Squares ( 6 kyu )  (0) 2017.12.11

+ Recent posts