I got the time out fixed and my results numbers are good.
Still won't verify....?
Keeps saying:
"The getNumbers method must return the array of numbers that satisfy the task conditions."
Here are the results I get with 1000 and 1000000. But I have also run a couple of bigger numbers as well.
So I am a bit baffled.
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407]
memory 492
time = 0
[1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834]
memory 2734
time = 0
Process finished with exit code 0
package com.codegym.task.task20.task2025;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
/*
Number algorithms
*/
public class Solution {
public static long[] getNumbers(long N) {
if(N <= 0)return new long[0]; // handle 0 and negatives
ArrayList <Long> res = new ArrayList<>(); // create an expandable array for collecting the result.
long[] factors = new long[10]; // create an array of 10 factored values starting at 1.
for (int j = 0; j < 10; j++){
factors[j] = j;
}
int fact = 1; // for counting factors
for (long i = 1;i < N; i++){ // for every natural number up to N
String number = String.valueOf(i); // convert the number (i) to a string
char[] digit = number.toCharArray(); // Break the string apart into individual chars
if (digit.length > fact) { // check to see if the number of digits has changed
fact++;
for (int j = 0; j < 10; j++) { // if it has re multiply the factors array and increment the fact counter,
factors[j] = factors[j] * j;
}
}
long total = 0;
for (char ch : digit){ // Use the factors array to match the digit and add it's value to the total
total += factors[Character.getNumericValue(ch)];
}
if (i == total){ // see if that total matches the original number and add it to the res array
res.add((long)i);
}
} // End of number search
Collections.sort(res); // sort the res
long[] result = new long[res.size()]; //convert the res to the required result array
for (int i = 0; i < res.size(); i++) {
result[i] = res.get(i);
}
return result;
}
public static void main(String[] args) {
long a = System.currentTimeMillis();
System.out.println(Arrays.toString(getNumbers(1000)));
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(1000000))); //1000000
b = System.currentTimeMillis();
System.out.println("memory " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (8 * 1024));
System.out.println("time = " + (b - a) / 1000);
}
}