Write a program to convert a binary number to a decimal number.
Binary Number: A number in base 2 is a binary number. Binary has digits 0 or 1.
Example 1:
Input:1101
Output:13
Example 2:
Input:11010
Output:26
Approach:
Java
public class BinaryToDecimal {public static void main(String[] args) {String binary = "11010";int decimal = binaryToDecimal(binary);System.out.println("Decimal is " + decimal);}public static int binaryToDecimal(String binary) {int decimal = 0;for (int i = 0; i < binary.length(); i++) {if (binary.charAt(i) == '1')decimal += Math.pow(2, binary.length() - i - 1);}return decimal;}}
C++
#include <bits/stdc++.h>using namespace std;//Function to convert from binary to decimalint binaryToDecimal(string s){int res=0;int n=s.size();for(int i=0;i<n;i++){if(s[i]=='1')res=res+pow(2,(n-i-1));}return res;}int main(){string str="1101";int decimal=binaryToDecimal(str);cout<<"Decimal is ";cout<<decimal<<"\n";return 0;}
No comments:
Post a Comment