+ 1

Why is the output of this code 7 and not 1001?

String a = “101”; String b = “010”; int a1 = Integer.parseInt(a,2); int b1 = Integer.parseInt(b,2); int sum = a1 + b1; System.out.print(sum); I’m confused with how .parseInt() works in this code.

6th Aug 2019, 8:37 PM
Samuel
Samuel - avatar
2 Respostas
+ 5
in parenthesis (a, 2) and (b,2)means that number in binary. a1 = 5 b1 = 2 a1 + b1 = 7
6th Aug 2019, 8:53 PM
notqueued
notqueued - avatar
+ 2
Integer.parseInt(a,2) returns the decimal value of a binary number (base 2 to base 10). "101" (binary) -> 5 (decimal) "010" (binary) -> 2 (decimal) 5 + 2 == 7.
6th Aug 2019, 8:52 PM
Diego
Diego - avatar