Let be an integer. We define a function which returns the cube of sum of digits of .
You are given two integers and . You have to find the value of the integer that is returned when the function is recursively applied times on .
Formally, you have to find the value of .
Example:
Input: n=3, k=2
Output: 729
Approach
Java
public class DigitCube {static long[] arr = new long[300];static {for (int i = 0; i < arr.length; i++) {arr[i] = i * i * i;}}public static void main(String[] args) throws Exception {long n = 3;long k = 2;int[] hash = new int[200];int count = 0;long ans = 0;long temp = n;while (count < k && hash[sod(temp)] == 0) {ans = arr[sod(temp)];hash[sod(temp)] = count + 1;temp = ans;count++;}if (hash[sod(temp)] != 0) {k -= hash[sod(temp)] - 1;count = count - hash[sod(temp)] + 1;}int val = (int) (k % count);while (val > 0) {ans = arr[sod(temp)];temp = ans;val--;}System.out.println(ans);}static int sod(long n) {int ans = 0;while (n > 0) {ans += (int) (n % 10);n /= 10;}return ans;}}
No comments:
Post a Comment