Without using bin(,2). Can anybody give me one line code convert decimal to binary?

• ``````def addBinary(self, a, b):
la=list(a)[::-1]
lb=list(b)[::-1]
aa=sum([ int(v)*2**i for i,v in enumerate(la)])#otherwise use aa==int(a,2)
bb=sum([ int(v)*2**i for i,v in enumerate(lb)])
res=aa+bb
return str(bin(res))[2:]#Can anybody give one line code to convert decimal to binary without using bin()?``````

• Convert decimal to binary? You don't make sense. Where do you have decimal? Nowhere. You only have an `int`! Your `str(bin(res))` also doesn't make sense, as `bin` of course already gives you a string, so applying `str` is completely pointless.

Also, what's wrong with `bin`?

Anyway, here's an alternative: `'{:b}'.format(res)`

• well, thank you for ur suggestion of using '{:b}'.format(res)
Yes, what's wrong with bin? I guess here I am looking for some more analytic way of calculating the binary instead of calling those build-in functions. The same problem in your suggestion, I am asking for clean self-coding efficient method.

well, to answer ur question, int belongs to decimal, and what's wrong by calling str() outside a string? If you are sure it returns a string, that is redundant, but I was not sure, so I just double check it.

• I am asking for clean self-coding efficient method.

I don't think that's possible in one line. Well, I see a way to do it "in one line":

``````b = lambda n: b(n/2) + str(n%2) if n else ''; return  b(res) or '0'
``````

But I that's neither clean nor efficient :-)

int belongs to decimal

Huh? What do you mean?

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.