Write a program to convert a given decimal number to a binary number.
Example 1:
Input:15
Output:1111
Approach
Java
public class DecimalToBinary {public static void main(String[] args) {int decimal = 15;String binary = decimalToBinary(decimal);System.out.println("Binary is " + binary);}public static String decimalToBinary(int decimal) {String binary = "";while (decimal > 0) {// if decimal%2==0 then append 0 else append 1if (decimal % 2 == 0) {binary = "0" + binary;} else {binary = "1" + binary;}decimal = decimal / 2;}return binary;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to convert the decimal//to binarystring decimalToBinary(int n){//varibale to store the final//resultstring res="";while(n>0){//if n%2==0 then appen 0if(n%2==0)res+='0';//if n%2==1 then appen 1elseres+='1';n=n/2;}//reverse the resultreverse(res.begin(),res.end());return res;}int main(){int num=15;string binary=decimalToBinary(num);cout<<"Binary is ";cout<<binary<<"\n";return 0;}
No comments:
Post a Comment