JavaScript,78 72 71个字符
我还将发布最初的解决方案,然后再提出问题。虽然已经有了一个更好的JavaScript答案:)
for(n=prompt(a=0),j=1;j<=n;j*=2)for(i=j;i<=n;i+=2*j)n<i+j&&a++;alert(a)
http://jsfiddle.net/Mk8zd/1/
这个想法来自某些“心灵阅读卡”,通过向他们显示卡片并让他们说出他们的号码在哪些卡片上是显而易见的,从而使您能够获得他人记住的数字。
It works because each number is a unique combination of 1
s / 0
s in binary. My solution checks on which "cards" the number is apparent so as to determine how many 1
s it has. It's just not very efficient, though...
I found this document which outlines the mind reading technique.