본문 바로가기
연습장

Playing with digits

by anothel 2021. 10. 21.

Some numbers have funny properties.

 

For example

 

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.

 

Solution

#include <cmath>

class DigPow {
public:
  static int digPow(int n, int p);
};

int DigPow::digPow(int n, int p) {
  int result = 0;
  int _n = n;
  int count = 0;
  while (0 < _n) {
    _n /= 10;
    count++;
  }

  _n = n;
  p += count;
  while (0 < _n) {
    result += pow(_n % 10, --p);
    _n /= 10;
  }

  return result % n == 0 ? result / n : -1;
}

 

mamcienahita의 코드

#include <cmath>
using namespace std;
class DigPow
{
public:
  static int digPow(int n, int p){
   long long sum=0;
   for(char digit : to_string(n)){
     sum+=pow(digit-'0',p++);
   }
   return (sum/n)*n==sum ? sum/n : -1;
  }
};

 

후기

신비한 특성의 수를 찾는 문제였다. 각 자리의 수를 뽑아내기 위해서 for문을 한번 썼고, 각 자리에 맞는 제곱을 하기 위해서 두 번째 for문을 썼다. 이게 아주 엄청나게 잘못 짜고 있는 코드라고 생각하고 있었는데, 다 풀고 나서 막상 남의 코드를 보니 대부분 for문을 두 번 썼더라. 그중 integer형식으로 받아온 수를 char 자료형으로 형 변환 후 '0'를 제거해서 사용하는 코드가 눈에 들어왔다. 음.. 이렇게도 할 수 있었구나.

p.s. 레벨이 6 kyu가 됐는데, 여전히 6 kyu문제를 풀고 있어서 그런지 경험치가 잘 안 오른다.. 레벨 올라가면 난이도가 확 올라가던데..

 

(url: https://www.codewars.com/kata/5552101f47fc5178b1000050)

 

728x90

'연습장' 카테고리의 다른 글

Mexican Wave  (0) 2021.10.25
Rectangle into Squares  (0) 2021.10.25
Bit Counting  (0) 2021.10.19
Convert string to camel case  (0) 2021.10.19
Sum of Digits / Digital Root  (0) 2021.10.19