0

I traced the following code, and one part doesn't make sense to me:

def bin_rep(n: int) -> str:
     """Return the binary representation of n
     >>> bin_rep(0)
     "0"
     >>> bin_rep(1)
     "1"
     >>> bin_rep(5)
     "101"
     """

     if n > 1:
         return bin_rep(n // 2) + bin_rep(n % 2)
     else:
         return str(n)

The part that I don't understand is, why are we adding bin_rep(n//2) and bin_rep(n%2). I know that without the addition this won't work, but I can't wrap my head around why the addition exists there.

1
  • 1
    Since bin_rep always returns a string, this is a string concatenation rather than an addition. Does that help you? Commented Aug 14, 2018 at 19:58

2 Answers 2

4

That's not addition. bin_rep returns a string. The + operator for type string is concatenation. Read this as

binary representation of n right-shifted a bit
    concatenated with
binary representation of n's right-most bit

Does that clear it up?

Sign up to request clarification or add additional context in comments.

Comments

1

bin_rep(n) returns the binary string representation of n.

The termination condition is n <= 1 which is bin_rep(0) -> '0' or bin_rep(1) -> '1'.

bin_rep(2) must return '10'. To do that it computes:

bin_rep(2 // 2) + bin_rep(n % 2)
bin_rep(1) + bin_rep(0)
'1' + '0'  # String concatenation, not decimal addition!
'10'

... which is the correct answer. That should help clear up your understanding.

1 Comment

Thank you very much, that helped me out a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.