Chatbox
    You don't have permission to chat.
    Load More
benjiharrison15

All is nothing (java)

6 posts in this topic

Consider the sequence of digits from 1 through N (N<=9) in increasing order:  1 2 3 4 ... N

 

Insert either a '+' (for addition) or a '-' (for subtraction) between each of the digits so that the 

resultant sum is zero. Print all possible combinations that sum to zero.

 

Example:   Enter number: 7

 

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

 

Example:  Enter number: 4

 

1-2-3+4=0

 

How do you do this in JAVA?????

Share this post


Link to post
Share on other sites
package zeus.code.AllIsNothing;

 

import java.util.Scanner;

 

public class AllIsNothing {

 

/**

* @param args

*/

private int range;

 

int getRange()

{

System.out.print("Enter the range : ");

Scanner s = new Scanner(System.in);

range=s.nextInt();

return range;

}

 

public void printResult(String result)

{

String[] arrResult = result.split(":");

String dispStrin = "";

 

for(int i = 0;i<arrResult.length;i++)

{

dispStrin = "";

for(int j =0;j<arrResult.length();j++)

{

if(arrResult.charAt(j)=='0')

dispStrin = dispStrin+'+'+(j+1)+"";

else

dispStrin = dispStrin+'-'+(j+1)+"";

 

}

 

System.out.println(dispStrin);

}

}

 

public String printZero(int range)

{

int bitSize =0;

String result="";

 

for(int i=0;i<=range-1;i++)

{

bitSize += Math.pow(2,i);

}

 

System.out.println("Bit Size : "+bitSize);

String arr = Integer.toBinaryString(bitSize);

System.out.println("Binary fromat of bitSize : "+arr);

 

int sum =0;

int fixedSize = arr.length();

 

 

 

for(int j=bitSize;j>1;j--)

{

arr = Integer.toBinaryString(j);

if(arr.length()<fixedSize)

{

while(arr.length()!=fixedSize)

arr = '0'+arr;

}

System.out.println("Bitsize value : "+arr);

sum = 0;

for(int i =1;i<=range;i++)

{

// System.out.println("Running inner for loop");

if(arr.charAt(i-1)=='0')

{

System.out.println("Adding "+sum+" + "+i);

sum = sum+i;

}

else

{

System.out.println("Substracting "+sum+" - "+i);

sum = sum-i;

 

}

}

 

System.out.println("Sum : "+sum);

if(sum == 0)

result = result+":"+arr+"";

 

}

 

System.out.println("Sequences are : "+result);

return result;

 

}

public static void main(String[] args) {

// TODO Auto-generated method stub

 

AllIsNothing ain = new AllIsNothing();

 

// System.out.println("The range is : "+ain.getRange());

 

ain.printResult(ain.printZero(7));

}

 

}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now