How To Find Binary For Negative No

Here Is My Code,
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int place = 1;
long ans = 0;
while(n != 0){
int rem = n % 2;
ans = ans + (rem * place);
n = n / 2;
place = place * 10;
}
System.out.println(ans);

}

}

For binary number fedcba , Decimal number = f.2^5 + e.2^4 + d.2^3 + ……+ a.2^0.

  • The idea is to extract the digits of given binary number starting from right most digit and keep a variable decvalue.
  • At the time of extracting digits from the binary number, multiply the digit with the proper base (Power of 2)
  • and add it to the variable dec_value.
  • At the end, the variable decvalue will store the required decimal number.

you can see this:


if this solves your doubt please mark it as resolved :slight_smile: