Place Values
1, 2, 4, 8…
Each bit position is a power of two, starting at 20 on the right.
Binary (base 2) uses only bits 0 and 1; decimal (base 10) is the everyday number system. This tutorial covers place values, a live preview, algorithm steps, worked Java examples, edge cases, and complexity.
1, 2, 4, 8…
Each bit position is a power of two, starting at 20 on the right.
Sum 2^i
Walk bits right-to-left; add 2^power for every 1 bit.
Built-in
Parse a binary string as base 2 and get a decimal int in one call.
Only 0 / 1
Reject empty strings and any character outside {0, 1}.
Try any bits
Type a binary string and convert it to decimal instantly.
Complexity
One pass over k bits; extra space stays O(1) beyond the input.
Binary-to-decimal conversion turns a base-2 string into a base-10 integer. Each bit contributes a power of two: the rightmost bit is 20, then 21, 22, and so on.
You can sum those place values by hand, or call Integer.parseInt(bits, 2). Classic example: 101010 → 32 + 8 + 2 = 42.
It trains place-value thinking, string loops, validation, and the habit of explaining O(k) bit complexity in interviews.
Only 1-bits contribute; 0-bits add nothing.
Anything outside 0/1 is not a binary string.
Manual loop for interviews; Integer.parseInt(s, 2) for apps.
int/long can overflow; prefer BigInteger for huge bit strings.
In short: for each 1-bit at position i (from the right), add 2i — or just call Integer.parseInt(bits, 2).
Given a binary string of 0s and 1s, return its decimal integer value.
// Example: "101010"
// 1*32 + 0*16 + 1*8 + 0*4 + 1*2 + 0*1 = 42 | Item | Type | Description |
|---|---|---|
bits | str | Non-empty string containing only characters 0 and 1. |
| Return / print | int | Decimal integer value of that binary number. |
function binaryToDecimal(s):
if s has characters other than 0 and 1:
return error
total = 0
power = 0
for bit from right to left in s:
if bit == '1':
total = total + (2 ^ power)
power = power + 1
return total | Method | Idea | Notes |
|---|---|---|
| Place-value loop | Add 2^i for each 1-bit from the right | Best for showing interview math |
Integer.parseInt(bits, 2) | Built-in base-2 parse | Shortest production style |
| Goal | Pattern |
|---|---|
| Validate bits | all(ch in "01" for ch in bits) |
| Walk right-to-left | for (i = len-1; i >= 0; i--) |
| Add place value | total += powerOfTwo |
| Built-in convert | Integer.parseInt(bits, 2) |
| Doubling method | total = total * 2 + bit left-to-right |
| Classic check | "101010" → 42 |
Same decimal answer — different clarity and interview signaling.
sum 2^iShows powers of two clearly; preferred whiteboard style
built-inIdiomatic Java for real applications
2*total + bitLeft-to-right Horner form; no reverse needed
manual firstExplain place values, then mention Integer.parseInt(s, 2)
Reach for binary-to-decimal drills when base conversion and bit place values matter.
Quick check of loops, powers, and input validation.
Makes 1, 2, 4, 8… feel concrete with a famous 42 example.
Same idea extends to octal, hex, and custom bases.
Bits show up constantly in networking and hardware topics.
Fractional binary (after a point) needs a different place-value story.
Key benefit: one short problem that covers powers of two, string loops, validation, and O(k) reasoning.
Enter a binary string (0 and 1 only) and convert it to decimal.
Three complete Java programs — place-value loop, Integer.parseInt(..., 2), and the doubling method. Click View Output to reveal sample console results.
Powers of two from the right — the interview classic.
Validate bits, walk right-to-left, and add a power of 2 for every 1 (no Math.pow).
public class Main {
static long binaryToDecimalManual(String bits) {
bits = bits.trim();
if (bits.isEmpty()) {
throw new IllegalArgumentException("Binary string must contain only 0 and 1");
}
long total = 0;
long powerOfTwo = 1;
for (int i = bits.length() - 1; i >= 0; i--) {
char ch = bits.charAt(i);
if (ch != '0' && ch != '1') {
throw new IllegalArgumentException("Binary string must contain only 0 and 1");
}
if (ch == '1') {
total += powerOfTwo;
}
powerOfTwo *= 2;
}
return total;
}
public static void main(String[] args) {
String binaryNumber = "101010";
long decimalNumber = binaryToDecimalManual(binaryNumber);
System.out.println("Binary: " + binaryNumber);
System.out.println("Decimal: " + decimalNumber);
}
} After validation, the loop starts at the rightmost bit with weight 1. Each 1 contributes the current power of two; zeros are skipped. Doubling the weight avoids Math.pow.
Same answer with the built-in parser.
Integer.parseInt(..., 2)Validate first, then let Java parse the base-2 string.
public class Main {
static int binaryToDecimalBuiltin(String bits) {
bits = bits.trim();
if (bits.isEmpty()) {
throw new IllegalArgumentException("Binary string must contain only 0 and 1");
}
for (int i = 0; i < bits.length(); i++) {
char ch = bits.charAt(i);
if (ch != '0' && ch != '1') {
throw new IllegalArgumentException("Binary string must contain only 0 and 1");
}
}
return Integer.parseInt(bits, 2);
}
public static void main(String[] args) {
String binaryNumber = "101010";
System.out.println("Binary: " + binaryNumber);
System.out.println("Decimal: " + binaryToDecimalBuiltin(binaryNumber));
}
} Integer.parseInt(bits, 2) interprets the string in base 2. Keeping your own validation gives clearer error messages than a bare NumberFormatException.
Horner / doubling form — no reverse needed.
For each bit from the left: total = total * 2 + bit.
public class Main {
static long binaryToDecimalDoubling(String bits) {
bits = bits.trim();
if (bits.isEmpty()) {
throw new IllegalArgumentException("Binary string must contain only 0 and 1");
}
long total = 0;
for (int i = 0; i < bits.length(); i++) {
char ch = bits.charAt(i);
if (ch != '0' && ch != '1') {
throw new IllegalArgumentException("Binary string must contain only 0 and 1");
}
total = total * 2 + (ch == '1' ? 1 : 0);
}
return total;
}
public static void main(String[] args) {
System.out.println(binaryToDecimalDoubling("1010"));
System.out.println(binaryToDecimalDoubling("00101"));
}
} Each step shifts the previous total one bit left (multiply by 2) and adds the next bit. Leading zeros do not change the value — 00101 is still 5.
Reject empty strings and any character that is not 0 or 1.
Right-to-left with powers, left-to-right with doubling, or call Integer.parseInt(s, 2).
Add each 1-bit’s contribution into a running total.
Return the total — that is the base-10 value of the binary string.
101010Trace the place-value method from the right. Positions: 0 … 5.
| Bit (right→left) | Power | Contribution | total |
|---|---|---|---|
0 | 0 | 0 | 0 |
1 | 1 | 2 | 2 |
0 | 2 | 0 | 2 |
1 | 3 | 8 | 10 |
0 | 4 | 0 | 10 |
1 | 5 | 32 | 42 |
Final decimal: 42 (= 32 + 8 + 2).
Where binary-to-decimal conversion shows up beyond the interview prompt.
Tests place value, loops, and validation together.
Example: write binaryToDecimal(s).
Makes 1, 2, 4, 8… memorable with 101010 → 42.
Example: chalkboard bit positions.
Some tools store compact bit masks as binary text.
Example: parse a permission bit string.
Same place-value idea with different bases.
Example: Integer.parseInt(s, 16) for hex.
Argue O(k) from the bit length convincingly.
Example: “how many loop iterations?”
Java int/long can overflow; use BigInteger for huge bit strings.
Example: discuss fixed-width overflow.
Pro Tip: keep validation in one helper so manual, doubling, and built-in paths share the same rules.
Why this pattern works well in interviews and classwork.
Place values are exactly what the loop computes.
Integer.parseInt(s, 2) keeps application code short after you know the theory.
A few integers suffice — O(1) extra space beyond the input string.
Empty / invalid-character cases give interviewers easy follow-ups.
Pro Tip: say “rightmost bit is 20” before coding — it prevents off-by-one power mistakes.
Small habits that keep binary conversion interview-ready.
Check non-empty and only 0/1 characters first.
In interviews, show the manual sum before Integer.parseInt(s, 2).
Call trim() so accidental spaces do not fail validation.
Assert the result is 42 — a fast golden test.
They are valid padding; do not strip them as invalid.
Pro Tip: dry-run 101010 on paper once — it locks in right-to-left powers faster than guessing.
Mistakes that commonly break binary-to-decimal solutions.
Treating the leftmost bit as 20 reverses place values.
→ Rightmost bit is power 0 for the classic method.
Digits like 2 or letters produce wrong results or cryptic errors.
→ Reject anything outside {0, 1} early.
Integer.parseInt("101010") without base 2 reads it as decimal one-hundred-one-thousand…
→ Always pass base 2: Integer.parseInt(bits, 2).
Padding zeros are valid binary.
→ Allow them; they do not change the value.
An empty string should error, not convert to 0 silently in every design.
→ Decide the policy and document it.
Check these inputs before calling the solution done.
Reject strings like 1021 or 10a1.
Return a clear error instead of converting.
00101 is still valid and equals 5.
Smallest non-empty cases — return 0 or 1.
int/long can overflow; JS live preview is capped for safety.
Trim spaces before validating characters.
Handy follow-ups interviewers sometimes ask.
Integer.parseInt(s, radix) works for any base from 2 to 36.Try these variations to lock in the pattern.
1021 and empty string00101Integer.parseInt(s, 2)Integer.parseInt(bits, 2) second.Quick Takeaway: sum 2i for each 1-bit (or call Integer.parseInt(bits, 2)) after validating the string.
| Program | Time | Extra space |
|---|---|---|
| Manual loop over bits | O(k) | O(1) |
Integer.parseInt(bits, 2) | O(k) | O(1) |
| Doubling method | O(k) | O(1) |
Binary-to-decimal conversion is a clean place-value exercise: validate the bits, then sum powers of two (or use Integer.parseInt(s, 2)). Master the manual loop first, then the doubling and built-in shortcuts.
Practice the three examples above, then continue to common divisors for another classic number-theory warm-up.
Always validate 0/1 input, remember the rightmost bit is 20, and state O(k) for k bits.
Integer.parseInt(bits, 2) as a shortcutInteger.parseInt(bits) without radix 2Convert base 2 the interview-friendly way.
Sum 2^i for 1-bits
DefinitionRightmost is 2^0
MathOnly 0 and 1
GuardInteger.parseInt(s, 2)
CodeO(k) time
AnalysisBinary 101010 means 32 + 8 + 2, so its decimal value is 42.
Learn how to find all positive integers that divide two numbers evenly.
9 people found this page helpful