Skip to content
DeepForgeby svx
All problems
EasyAlgorithmsal-308

Varint Size

Problem

Return the number of bytes needed to encode a non-negative integer as a base-128 varint, where every byte stores 7 payload bits and the high bit is a continuation flag.

Zero still needs one byte, so the size is at least 1. Assume n >= 0.

Hint

Shift the value right by 7 bits per byte until nothing is left.

Test cases

case 1
in: [0]
expected: 1
case 2
in: [127]
expected: 1
case 3
in: [128]
expected: 2
case 4
in: [16384]
expected: 3
case 5
in: [2097151]
expected: 3
case 6
in: [2097152]
expected: 4
Starter codePython
def varint_size(n):
    # Your code here
    pass

6 test cases · run your code against them in the editor