chaibs

loops-hw5

Dec 27th, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class hw5 {
  4.  
  5.     public static void main(String[] args) {
  6.         int num = 0, loc = 1, newNum = 0;
  7.  
  8.         Scanner s = new Scanner(System.in);
  9.  
  10.         System.out.println("Please enter a number:");
  11.         num = s.nextInt();// getting number from user
  12.  
  13.         while (num > 0) {// as long as the num2 bigger then 0 continue
  14.             if (num % 2 == 0) {// checking if mod is 0
  15.                 newNum += 0 * loc;// adding 0 to the binary number from the left to the right
  16.             } else {// if mod is 1
  17.                 newNum += 1 * loc;// adding 1 to the binary number from the left to the right
  18.             }
  19.             num /= 2;// dividing number in 2
  20.             if (num > 0) {// if number is not 0
  21.                 loc *= 10;// multiply the digit location in 10 for next adding
  22.             }
  23.         }
  24.         System.out.println("The binary number is " + newNum);// result
  25.     }
  26.  
  27. }
Advertisement
Add Comment
Please, Sign In to add comment