pls help me with this
the user enters a number n.consider the sequence from 1 through n in ascending order.insert either '+' or'-' between each of the digits so that the resultant sum is zero.
for eg:
input=7
output= 1+2-3+4-5-6+7=0
1+2-3-4+5+6-7=0
1-2+3+4-5+6-7=0
1-2-3-4-5+6+7=0
however when i programmed it i only got the first two outputs.the ones where + is the first operator..but the code didn't print the next two...pls help or find an error in the following code(it's happened with other inputs too)

import java.io.*;
public class zerocombination
{
public String toBin(int x)// this function converts a given number to its binary form
{
String str="";
while(x!=0)// dividing by base and building up the string in reverse eventually gives the binary form
{
str=(x%2)+str;
x/=2;
}
return str;
}
public void main()throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER A NUMBER");
int num=Integer.parseInt(br.readLine());// accepting a number
int n=(int)(Math.pow(2,num-1));
boolean flag=false;
String str[]=new String[n];// creating array in which combination s will be stored
String copy="";
// following loop converts all numbers from 0 to 2^(n-1) to binary.the binary forms represents all the combinations in which the consecutive numbers can be added 
for(int i=0;i<n;i++)
{
str[i]=toBin(i);
while(str[i].length()<num)
str[i]="0"+str[i];
int exp=1;
String ex="1";
for(int j=2;j<=num;j++)
{
int x=((int)(str[i].charAt(j-2)))-48;
if(x==0)
{
ex+="+"+j;
exp+=j;
}
else
{
exp-=j;
ex+="-"+j;
}
}
// this is done to prevent repetition
if(exp==0&&ex.equals(copy)==false)
{
copy=ex;
flag=true;
System.out.println(ex+"=0");
}
}
if(flag==false)
System.out.println("NO SUCH EXPRESSION");
System.out.println();System.out.println();
}
}

Is Your problem:
Finding the correct algorithm?
Or is it writing a correct program to follow your algorithm?

Can you explain the algorithm you are trying to program? What are the steps you need to take to solve the problem?

Can you edit your post and wrap the code in code tags to preserve the formatting.
The posted code is hard to read.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.