954,545 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

ZeroCombination need help

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();
}
}
desert564
Light Poster
30 posts since Feb 2011
Reputation Points: 10
Solved Threads: 0
 

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?

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

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

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: