How to return as a string in recursive?

Viewed 46

I'm doing decimal to binary using recursion method. However, I was unable to convert it to string using the code below. Any help? <3

def to_binary(d):
  if d == 0:
    return str(0)
  else:
    return str(d % 2 + 10 * to_binary(int(d // 2)))

result = to_binary(nums)
print("Result: " + result)

It's always giving errors:

  • unsupported operand type(s) for +: 'int' and 'str'

Updated

3 Answers

Likely the formula in the last line is wrong.

Your function should return a string. But then the last line would try to add and multiply a number with a string - what result do you expect?

I suggest this last line:

return to_binary(int(d // 2))) + str(d % 2)

In your last line has a mistake.for example consider 3 converts to binary.it must be to_binary(3//2) = to_binary(1) + 3%2=1

def to_binary(d):
  if d == 0:
    return str(0)
  elif(d==1):
     return str(1)
  else:
    return str(to_binary(d // 2)+str(d%2))

Well bro the error is pretty straight forward. Here: return str(d % 2 + 10 * to_binary(int(d // 2))) you call to_binary, which returns a String, but then try to add it with a number d % 2.

Simply change that line to: return str(d % 2 + 10 * int(to_binary(int(d // 2)))). This should solve your error.

Related