Skip to content

Instantly share code, notes, and snippets.

@googya
Last active August 29, 2015 13:56
Show Gist options
  • Save googya/9133330 to your computer and use it in GitHub Desktop.
Save googya/9133330 to your computer and use it in GitHub Desktop.
计算一个数字数组中 1 的个数(递归方式)
def count_one(a)
return 0 if a <= 0
( a % 10 ) == 1 ? 1 + count_one( a / 10 ) : count_one( a / 10 )
end
(1..100).to_a.inject(0){|sum, a| sum += count_one(a) }
@googya
Copy link
Author

googya commented Mar 21, 2014

def count_one(a)
  return 1 if a == 1
  return 0 if a < 10

  dived = 10 ** (a.to_s.size - 1)  
  div, rem = a.divmod (dived)

  count_one(div) + count_one(rem)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment