简体   繁体   中英

print all binary numbers of size n using recursion

i am trying to print all size n binary numbers, for example if size is 3 , i want to print all numbers from 0 to (2^3)-1 in binary form, below if my code implementating, it prints 000 and gives me this error

"Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.getChars(String.java:854)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:391)
at java.lang.StringBuilder.append(StringBuilder.java:119)
at java.lang.StringBuilder.<init>(StringBuilder.java:93)
at NBinary.tobinary(NBinary.java:11)
at NBinary.tobinary(NBinary.java:12)". 

String temp = str+x; is line 11
tobinary(temp, size); is line 12

below is my code

public class NBinary {

static int arr[] = {0,1};
static void tobinary(String str,int size){

    if(str.length() == size){
        System.out.println(str);
    }
    for(int x : arr){
        String temp = str+x;
        tobinary(temp, size);
    }


}

public static void main(String[]args){

    tobinary("", 3);

}

}

please help me find the error. thanks

One problem is that you are not giving any Recursion Termination condition. So the function recurses infinitely. No condition is there to cease the calling.

That is why the stack allocated for the function call runs out of space and you get StackOverflowError .

See more here:

http://docs.oracle.com/javase/7/docs/api/java/lang/StackOverflowError.html

What is a StackOverflowError?

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