Binary count (Library 2.0) - 10進数を2進数に変換
どんな問題?
Binary count
http://www.checkio.org/mission/binary-count/
正の整数を2進数に変換して、1が何個あるか数えよ。
例題:
checkio(4) == 1 checkio(15) == 4 checkio(1) == 1 checkio(1022) == 9
どうやって解く?
数字を2進数に変換するには、bin() か format() を使う。
>>> bin(9) '0b1001' >>> format(9, 'b') '1001' >>> '{0:b}'.format(9) '1001'
bin()だと'0b'が付くので、0を数えるなら気をつけるべきだが、今回は1を数えるので、bin()でいい。
def checkio(number): return bin(number).count('1')
なんか簡単すぎる。
他の人の答えを見ても、ほとんどの人が同じ解答。
うーん、次に行くか。