"""Any base to decimal
>>> CHECK THE SOURCE! <<<
Conversion of number from any base to decimal!
Answer by paw88789 on Nov 2, 2017 on Math StackExchange:
+------------------------------------------------------------------------+
A similar thing occurs if someone reads you, digit-by-digit,...
...left-to-right, a base ten numeral:
E.g. The actual numeral is 3702, but you only get one digit at a time:
[3] Current value is 3.
[7] Current the value is 3⋅10+7=37.
[0] Current the value is 37⋅10+0=370.
[2] Current the value is 370×10+2=3702.
End of number. The last current value is the actual value.
At each step, you multiply the previous total by the base...
...and add the next digit.
+------------------------------------------------------------------------+
"""
//* How to convert a decimal number into a binary number
#include <bits/stdc++.h>
using namespace std;
class NumberConversion
{
int n = 0, count = 0, ans = 0;
public:
void decimalToBinary(int n)
{
this->n = n;
while (this->n != 0)
{
int rem = this->n % 2;
this->n /= 2;
ans += rem * pow(10, count);
count++;
}
}
void display()
{
cout << ans << endl;
}
};
int main()
{
int number = 0;
cin >> number;
NumberConversion num1;
num1.decimalToBinary(number);
num1.display();
return 0;
}
#include <stdio.h>
int main()
{
int num, binary_val, decimal_val = 0, base = 1, rem;
printf("Insert a binary num (1s and 0s)
");
scanf("%d", &num);
binary_val = num;
while (num > 0)
{
rem = num % 10;
decimal_val = decimal_val + rem * base;
num = num / 10 ; //these are the correct lines
base = base * 2; //these are the correct lines
}
printf("%d
", binary_val);
printf("%d
", decimal_val);
return 0;
}
import java.util.Scanner;
public class BinaryToDecimal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
String binary = sc.next();
// This is one line solution for binary to decimal in java
System.out.println(Integer.parseInt(binary,2));
//This solution is based on formula for binary to decimal conversion
int n=0,dec=0;
for(int i=binary.length()-1;i>=0;i--)
{
dec = dec + Integer.parseInt(String.valueOf(binary.charAt(i)))*(int)Math.pow(2,n);
n++;
}
System.out.println(dec);
}
}