Skip to main content

Rebuilding a Number

A number is not a thing you have - it is a thing you wrote down. 1256 is shorthand for 1⋅103+2⋅102+5⋅101+6⋅1001 \cdot 10^3 + 2 \cdot 10^2 + 5 \cdot 10^1 + 6 \cdot 10^0, and the only reason the base is 10 is that nobody wrote it next to the digits. Bit Basics covers that groundwork and this page assumes it.

What it gives you is two primitives, and they are the whole chain:

n, d = divmod(n, B) # PEEL - take the lowest digit off, shrink n
acc = acc * B + d # BUILD - shift acc up one column, drop d into the gap

They are inverses, and they disagree about direction. Peel hands you digits least-significant first. Build wants them most-significant first. Every problem below is a choice of base, a choice of which primitive, and an answer to that disagreement - ignore it, undo it with a deque, or exploit it on purpose to reverse a number.

ndigit outacc = acc * 10 + d125666125565122652116521peel drains the low endbuild fills the high end
Feed peel straight into build and the digits arrive in the wrong order on purpose. The mismatch is not a bug to route around - it is Reverse Integer.

Change the base and nothing about that picture changes except the column weights. Convert something and watch both halves run - the decode phase is build, the encode phase is peel:

From base
To base
1. read 1256 in base-10
10311000102220010155010066
= 1256 (decimal)
2. divide 1256 by 2, keep remainders
nn ÷ 2n % 2 (digit)
12566280
6283140
3141570
157781
78390
39191
1991
941
420
210
101
read remainders bottom-to-top10011101000

Peel, and throw the order away​

Otto, your interviewer

Count Digits in a Number​

Count Digits in a Number

GeeksforGeeks
Easy

Digit-Extraction Loop

class Solution:
def countDigits(self, n):
digits = 0
while n:
n, rem = divmod(n, 10)
digits += 1
return digits
top ↑
Otto, your interviewer

258. Add Digits​

258

Add Digits

LeetCode
Easy

Digit-Sum Loop

class Solution:
def addDigits(self, num: int) -> int:
if num // 10 == 0:
return num
total = 0
while num:
num, rem = divmod(num, 10)
total += rem
return self.addDigits(total)
top ↑
Otto, your interviewer

1837. Sum of Digits in Base K​

1837

Sum of Digits in Base K

LeetCode
Easy

Digit-by-Digit Accumulate

class Solution:
def sumBase(self, n: int, k: int) -> int:
total = 0
while n:
n, rem = divmod(n, k)
total += rem
return total
top ↑

Peel, when the order does matter​

Otto, your interviewer

Decimal to binary​

Decimal to binary

GeeksforGeeks
Easy

Digit-by-Digit Rebuild

import collections
 
 
class Solution:
def decToBinary(self, n):
ans = collections.deque()
while n:
n, rem = divmod(n, 2)
ans.appendleft(str(rem))
return "".join(ans)
top ↑
Otto, your interviewer

504. Base 7​

504

Base 7

LeetCode
Easy

Digit-by-Digit Rebuild

class Solution:
def convertToBase7(self, num: int) -> str:
if num == 0:
return "0"
neg = num < 0
num = abs(num)
res = collections.deque()
while num:
num, rem = divmod(num, 7)
res.appendleft(str(rem))
if neg:
res.appendleft("-")
return "".join(res)
top ↑
Otto, your interviewer

405. Convert a Number to Hexadecimal​

405

Convert a Number to Hexadecimal

LeetCode
Easy

Digit-by-Digit Rebuild

class Solution:
def toHex(self, num: int) -> str:
if num == 0:
return "0"
if num < 0:
num = 2**32 + num
res = collections.deque()
hex_arr = "0123456789abcdef"
while num:
num, rem = divmod(num, 16)
res.appendleft(hex_arr[rem])
return "".join(res)
top ↑
Otto, your interviewer

168. Excel Sheet Column Title​

168

Excel Sheet Column Title

LeetCode
Easy

Digit-by-Digit Rebuild

class Solution:
def convertToTitle(self, columnNumber: int) -> str:
col = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
res = collections.deque()
while columnNumber:
columnNumber, rem = divmod(columnNumber - 1, 26)
res.appendleft(col[rem])
return "".join(res)
top ↑

Build, when someone else supplies the digits​

Otto, your interviewer

171. Excel Sheet Column Number​

171

Excel Sheet Column Number

LeetCode
Easy

Base-26 Digit Rebuild

class Solution:
def titleToNumber(self, columnTitle: str) -> int:
col = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
col = {char: idx + 1 for idx, char in enumerate(col)}
total = 0
for char in columnTitle:
total = total * 26 + col[char]
return total
top ↑
Otto, your interviewer

1290. Convert Binary Number in a Linked List to Integer​

1290

Convert Binary Number in a Linked List to Integer

LeetCode
Easy
FIG. CONVERT BINARY NUMBER IN A LINKED LIST T● INTERACTIVE
visualization loads as you reach it
def getDecimalValue(head):
number = 0
curr = head
while curr:
number = number * 2 + curr.val
curr = curr.next
return number
top ↑
49051cur = 4cur = 49cur = 40 (leaf)cur = 495cur = 491down: cur = cur * 10 + node.valup: cur //= 10
129 on [4,9,0,5,1]. The accumulator is built on the way down and peeled on the way back up, so it always holds the digits of the path you are currently standing on - 495 + 491 + 40 = 1026.
Otto, your interviewer

129. Sum Root to Leaf Numbers​

129

Sum Root to Leaf Numbers

LeetCode
Medium

Each root-to-leaf path spells a decimal number (most significant digit at the root). Carry the running value down with cur_decimal = 10 * cur_decimal + node.val, and add it to the total whenever a leaf is reached. This mirrors the binary version (1022), swapping base 2 for base 10.

DFS (Recursive)

FIG. SUM ROOT TO LEAF NUMBERS● INTERACTIVE
visualization loads as you reach it
def sumNumbers(self, root: Optional[TreeNode]) -> int:
def recursion(node):
nonlocal total, cur_decimal
if node:
cur_decimal = 10 * cur_decimal + node.val
if not node.left and not node.right:
total += cur_decimal
recursion(node.left)
recursion(node.right)
cur_decimal //= 10
 
cur_decimal = total = 0
recursion(root)
return total
top ↑
Otto, your interviewer

1022. Sum of Root To Leaf Binary Numbers​

1022

Sum of Root To Leaf Binary Numbers

LeetCode
Easy

Each root-to-leaf path spells a binary number (most significant bit at the root). Carry the running value down the path with cur_binary = 2 * cur_binary + node.val, and add it to the total whenever a leaf is reached.

DFS (Recursive)

FIG. SUM OF ROOT TO LEAF BINARY NUMBERS● INTERACTIVE
visualization loads as you reach it
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
def recursion(node):
nonlocal total, cur_binary
if node:
cur_binary = 2 * cur_binary + node.val
if not node.left and not node.right:
total += cur_binary
recursion(node.left)
recursion(node.right)
cur_binary //= 2
 
cur_binary = total = 0
recursion(root)
return total
top ↑

Peel and build in the same loop​

Otto, your interviewer

7. Reverse Integer​

7

Reverse Integer

LeetCode
Medium

Digit-by-Digit Rebuild

class Solution:
def reverse(self, n: int) -> int:
res = 0
neg = n < 0
if neg:
n = -n
while n:
last_bit = n % 10
n = n // 10
res = res * 10 + last_bit
if not -(2**31) <= res <= 2**31 - 1:
return 0
return -res if neg else res
top ↑
Otto, your interviewer

9. Palindrome Number​

9

Palindrome Number

LeetCode
Easy

Full Reversal

class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
original = x
rev = 0
while x:
x, rem = divmod(x, 10)
rev = rev * 10 + rem
return rev == original
top ↑
Otto, your interviewer

190. Reverse Bits​

190

Reverse Bits

LeetCode
Easy

Bit by Bit

FIG. 190 BITWISE● INTERACTIVE
visualization loads as you reach it
class Solution:
def reverseBits(self, n: int) -> int:
r = 0
for i in range(32):
r = (r << 1) | (n & 1)
n >>= 1
return r
top ↑

Digits as a window​

Otto, your interviewer

2269. Find the K-Beauty of a Number​

2269

Find the K-Beauty of a Number

LeetCode
Easy

Sliding Window

FIG. 2269 FIND THE K BEAUTY OF A NUMBER● INTERACTIVE
visualization loads as you reach it
class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
n = int(math.log10(num)) + 1
left = right = 0
ans = sub_num = 0
 
isDivisible = lambda: int(num) % sub_num == 0 if sub_num != 0 else 0
 
while right < n:
# Expansion
while right < n and right - left < k:
power = 10 ** (n - right - 1)
digit = (num // power) % 10
sub_num = sub_num * 10 + digit
right += 1
# Logic
ans += isDivisible()
# Shrinking
sub_num = sub_num % (10 ** (k - 1))
left += 1
return ans
top ↑

The constraint matrix​

ProblemBasePrimitiveDigits come fromWhat it does about order
count-digits Count Digitsthe hub10PeelThe numberNothing - the digit is discarded
258 Add Digitsfrom count-digits10PeelThe numberNothing - it sums, then recurses to a digital root
1837 Sum of Digits in Base Kfrom 258kPeelThe numberNothing - the base is the only delta
dec-to-bin Decimal to Binaryfrom 18372PeelThe numberdeque.appendleft - digits are the answer now
504 Base 7from dec-to-bin7PeelThe numberdeque.appendleft
405 Convert a Number to Hexadecimalfrom 50416PeelThe numberdeque.appendleft, plus a digit table past 9
168 Excel Sheet Column Titlefrom 40526PeelThe numberdeque.appendleft, and divmod(n - 1, 26) - there is no zero digit
171 Excel Sheet Column Numberfrom 16826BuildA string, left to rightNothing to fix - they already arrive high-first
1290 Convert Binary Number in a Linked Listfrom 1712BuildA linked list, head firstNothing to fix
129 Sum Root to Leaf Numbersfrom 129010BuildA root-to-leaf pathNothing to fix; peels on the way back up to unwind
1022 Sum of Root to Leaf Binary Numbersfrom 1292BuildA root-to-leaf path129 with 10 replaced by 2
7 Reverse Integerfrom count-digits10BothThe numberExploits it - peel-then-build is the reversal
9 Palindrome Numberfrom 710BothThe numberExploits it, then stops at the midpoint (x > rev)
190 Reverse Bitsfrom 72BothThe numberExploits it over a fixed 32 columns, not until empty
2269 Find the K-Beauty of a Numberfrom 710BothThe number, by column indexBuilds right, truncates left with % 10 ** (k - 1)

Read the last two columns together. The base column is noise - it changes on almost every row and changes nothing about the code. The work is always in the last column: whether you can ignore the direction peel forces on you, have to spend a deque undoing it, or can arrange for it to be the answer.