Question

5.14 LAB: Convert to binary Write a program that takes in a positive integer as input,...

5.14 LAB: Convert to binary

Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:

As long as x is greater than 0
   Output x modulo 2 (remainder is either 0 or 1)
   Assign x with x divided by 2

Note: The above algorithm outputs the 0's and 1's in reverse order.

Ex: If the input is:

6

the output is:

011

6 in binary is 110; the algorithm outputs the bits in reverse

In Python, please. Thank you

2 1
Add a comment Improve this question Transcribed image text
✔ Recommended Answer
Answer #1
if __name__ == '__main__':
    user_num = int(input())
    while user_num > 0:
        print(user_num % 2, end='')
        user_num //= 2
    print()

Add a comment
✔ Recommended Answer
Answer #3

ANSWER :

This is a very straight forward question, the algo is given, and we have to just put a corresponding code to fetch the result.

CODE:

"""algorithms:
    As long as x is greater than 0
   Output x modulo 2 (remainder is either 0 or 1)
   Assign x with x divided by 2"""
# taking user input
x = int(input())
str1 = ''
# using while loop to iteratively divide by 2
while x > 0:
    out = x % 2   # the remainder 0 or 1
    str1 += str(out)   # storing the remainder in str1
    x = x//2
print("output from algorithm : ",str1)

OUTPUT :

THANK YOU...!!!!

Add a comment
Answer #4
import java.util.Scanner; 

public class LabProgram {
   public static void main(String[] args) {
      /* Type your code here. */
      Scanner scnr = new Scanner(System.in);
      int x;
      x = scnr.nextInt();
      String str1 = "";
      
      while(x>0){
         int out = x % 2;
         String s = String.valueOf(out); 
         str1 = str1 + s;
         x = x / 2;
         }
         System.out.println(str1);
   }
}

Here is an answer to 4.14 Lab: Convert to binary in Java

Add a comment
Answer #2


sum_num = int(input())

while (sum_num > 0) :
 print(sum_num % 2, end='')
 sum_num //= 2
print()
answered by: FiKR0
Add a comment
Know the answer?
Add Answer to:
5.14 LAB: Convert to binary Write a program that takes in a positive integer as input,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT