Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class hw5 {
- public static void main(String[] args) {
- int num = 0, loc = 1, newNum = 0;
- Scanner s = new Scanner(System.in);
- System.out.println("Please enter a number:");
- num = s.nextInt();// getting number from user
- while (num > 0) {// as long as the num2 bigger then 0 continue
- if (num % 2 == 0) {// checking if mod is 0
- newNum += 0 * loc;// adding 0 to the binary number from the left to the right
- } else {// if mod is 1
- newNum += 1 * loc;// adding 1 to the binary number from the left to the right
- }
- num /= 2;// dividing number in 2
- if (num > 0) {// if number is not 0
- loc *= 10;// multiply the digit location in 10 for next adding
- }
- }
- System.out.println("The binary number is " + newNum);// result
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment