1
I’m trying to create an algorithm that converts base 10 to base 2. It is apparently converting, but is not returning the right binary value.
package basicojava;
import java.util.Scanner;
public class Ex13 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int num;
int resto;
System.out.println("Digite um numero em decimal: ");
num = sc.nextInt();
do {
resto = num % 2;
num = num / 2;
System.out.println(resto);
} while (num != 0);
}
}
What do I need to do to get it to return the right value? I would like a solution only using logic. I know that java has a method to do this.
Besides, how can I invert these values without using vector?
Good afternoon. The way I did it is wrong? Because in my studies I have not studied method. I’m trying to do it purely with the basics of programming logic. Why use Stringbuffer? And binary.append?
– Hardysec
There enters the question that you have not reversed the writing form as it is done in that line
System.out.println(binario.reverse().toString()). As with thereverce()the number will be in the correct order– R.Santos
That
StringBuffer binario = new StringBuffer()you can trade for thisString binario = " "and then on that linebinario.append(b)trade for thisbinario = binario + bthis way you will be concatenating the value ofbinarioplus the value ofb– R.Santos