I have quite a story with this task. First, none of the requirements was met, even though the output was as expected. Then I changed the Math.pow(...) method for my own digitToThePower(long a, long b) to save time and space in memory (as I understood from the help section that might be the problem). Then, for some weird reason, the validator marked the first three points as passed, even though nothing else changed. Well, ok. Now it says, "The getNumbers method must return the array of numbers that satisfy the task conditions". But it does. [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407] in the first case, and [1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834] in the second one. What am I missing?
package com.codegym.task.task20.task2025;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
Number algorithms
*/
public class Solution {
public static long[] getNumbers(long N) {
long[] result = null;
List<Long> cringeNumbers = new ArrayList<>();
for (long l = 1; l < N; l++) {
String S = String.valueOf(l);
int M = S.length();
long sum = 0;
for (int i = 0; i < M; i++) {
int digit = Integer.parseInt(String.valueOf(S.charAt(i)));
long digitToM = digitToThePower(digit, M);
sum = sum + digitToM;
}
if (l == sum) {
cringeNumbers.add(l);
}
}
result = new long[cringeNumbers.size()];
for (int x = 0; x < cringeNumbers.size(); x++) {
result[x] = cringeNumbers.get(x);
}
return result;
}
public static void main(String[] args) {
long a = System.currentTimeMillis();
System.out.println(Arrays.toString(getNumbers(1000)));
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]
long b = System.currentTimeMillis();
System.out.println("memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (8 * 1024)); // returns kilobytes, doesn't it?
//System.out.println("memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024) + " MB");
System.out.println("time = " + (b - a) / 1000);
a = System.currentTimeMillis();
System.out.println(Arrays.toString(getNumbers(1000000)));
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834]
b = System.currentTimeMillis();
System.out.println("memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (8 * 1024)); // return kilobytes again, doesn't it?
//System.out.println("memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024) + " MB");
System.out.println("time = " + (b - a) / 1000);
}
public static long digitToThePower(long a, long b) {
long result = a;
if (b == 1) return result;
else {
for (int counter = 1; counter < b; counter++) {
result = result * a;
}
return result;
}
}
}