I get great timing and decent memory usage in IntelliJ Idea. The results also seem to be correct.
Do I miss something? Is there are corner case I am missing out?
Thanks!
package com.codegym.task.task20.task2025;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;
/*
Number algorithms
*/
public class Solution {
public static void main(String[] args) {
long a = System.currentTimeMillis();
System.out.println(Arrays.toString(getNumbers(54748)));
long b = System.currentTimeMillis();
System.out.println("memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (8 * 1024));
System.out.println("time = " + (b - a) / 1000);
a = System.currentTimeMillis();
System.out.println(Arrays.toString(getNumbers(100000000)));
b = System.currentTimeMillis();
Runtime t = Runtime.getRuntime();
System.out.println("memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (8 * 1024));
System.out.println("time = " + (b - a) / 1000);
}
public static int calculatePows(int length, int piece){
int result = piece;
for (int i = 1; i <length ; i++) {
result *= piece;
}
return result;
}
public static long[] getNumbers(long N) {
if (N <= 0)
return new long[0];
List<Integer> resultList = new ArrayList<>();
for (int i = 1; i <N ; i++) {
ResourceBundle.clearCache();
String currentNum = String.valueOf(i);
int S = 0;
for (int j = 0; j <currentNum.length() ; j++) {
int piece = (currentNum.charAt(j) - '0');
S += calculatePows(currentNum.length(), piece);
}
if (S == i) {
resultList.add(S);
}
}
long[] result = new long[resultList.size()];
for (int i = 0; i <resultList.size(); i++) {
result[i] = resultList.get(i);
}
return result;
}
}