简体   繁体   中英

How can I print out n numbers that satisfy the condition

I have written a code that would return either 1 or 4 as the output, and here it is

public static int findSum(int k) {
            int sum = 0;
            boolean foundNonZero = false;
            for (; k != 0; k /= 10) {
                if (foundNonZero) {
                    sum += (k % 10)*(k % 10);
                } else {
                    foundNonZero = k % 10 != 0;
                }
            }
            return sum;
        }

Now, I'm trying to write a function public static long[] firstK(int k) that would return k numbers starting from 0 that would satisfy the condition that findsum = 1.

I'm struggling to understand how to do it, despite reading Java syntax and information. and here is my code so far:

public static long[] firstK(int k) {
    while (int x = 0;) {
        if (findSum(x) = 1;)
            System.out.println(x);
        } 

I know that int(k) isn't used in this, but I have no idea how to implement it. Any help would be greatly appreciated:)

Maybe something like this:

public static List<Integer> firstK(int k) {
    List<Integer> result = new ArrayList<>();
    for (int x = 0 ; result.size() < k ; x++)
        if (findSum(x) == 1)
            result.add(k);
    return result;
}

If you really want an array rather than a List, I would still use a List to compute the result. I would then create an array from that list and return that as the function's result to have the function return a int[] or long[] . I can't see why you'd want to return long[] or List<Long> rather than int[] or List<Integer> , I doubt the code involved would ever be given the chance to iterate past the maximum integer value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM