CodeWars 일백 열 다섯 번째 문제
Updated:
A Rule of Divisibility by 13
public static long thirt(long n) {
long remainder = n;
do {
n = remainder;
remainder = makeRemainder(makeSequence(n));
} while(n != remainder);
return remainder;
}
private static int makeRemainder(int[] sequence) {
int remainder = 0;
int[] cycle = {1, 10, 9, 12, 3, 4};
for(int i = 0, j = 0; i < sequence.length; i++, j++) {
if(j == cycle.length) {
j = 0;
}
remainder += sequence[i] * cycle[j];
}
return remainder;
}
private static int[] makeSequence(long n) {
int[] sequence = new int[(int)Math.log10(n) + 1];
for(int i = 0; i < sequence.length; i++) {
sequence[i] = (int) (n % 10);
n = n / 10;
}
return sequence;
}
- 문제는 굉장히 쉬웠다.
- 하지만 위의 코드를 더 간단히… 재귀로 풀면 쉽게 풀 수 있다.
private static final int[] seq = new int[]{1,10,9,12,3,4};
public static long thirt(long n) {
long v = 0, m = n;
int p = 0;
while (m>0) {
v += (m%10)*seq[p++%6];
m /= 10;
}
return v == n ? v : thirt(v);
}