A question in flipping a number

  • Thread starter Thread starter transgalactic
  • Start date Start date
AI Thread Summary
The discussion revolves around a programming challenge to convert a decimal number to its binary representation. The original code provided by the user produces a reversed binary output, such as "001" for the decimal number 4 instead of "100". The issue arises because the binary digits are appended to the end of the string rather than the beginning. To correct this, the order of appending should be reversed. Additionally, a suggestion is made to utilize Java's built-in functions for base conversion, which can simplify the process significantly. The built-in method allows for easy conversion from decimal to binary without manual string manipulation.
transgalactic
Messages
1,386
Reaction score
0
i was told to build a program that transforms a number from deximal basis
into binary basis

i have built it but i get the resolt reversed
for the number 4 i get 001 instead of 100
i know it happening because the last digit comes last

how to change this method so it will show me the right resolt??

Code:
public class binar {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
binary(4);
	}
	public static void binary(int n){
		binar(n,"");
	}
public static void binar(int n,String str){
	if (n==0){
		System.out.println(str);
	}
	else
		binar((int)Math.floor(n/2),str+(n%2));
}
}
 
Technology news on Phys.org
That's pretty inefficient there!

In any case, your problem is that str is the end of your string, not the start. Reverse the order that you're appending them.
 
how can i reverse the order??
 
Look at the last line of your code (other than the two }s), it should be pretty obvious. You're sticking it on the wrong end.
 
thanks
 
transgalactic said:
i was told to build a program that transforms a number from deximal basis
into binary basis

If you use Java, you can just use its built-in function to do so:
Code:
int fromBase = 10;
int toBase = 2;

Integer.toString (Integer.parseInt (args [0], fromBase), toBase);

Next, you can just run your program conveniently like:
Code:
java BaseNToMConverter 82733


Eus
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.
Back
Top