Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
Ruby
[QUIZ] Happy Numbers (#93)
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Bob Showalter, post: 4525824"] I'm just posting my happy? method since it's a little different from the others. I opted for a recursive solution that records its results as it goes. I set the cache value to false before recursing; if the number winds up being happy, the true values are set as the recursion unwinds. class Integer # cache of happy true/false by number @@happy = Hash.new # sum of squares of digits def sosqod sum = 0 self.to_s.each_byte { |d| d -= ?0; sum += d * d } sum end # am I a happy number? def happy? return true if self == 1 return @@happy[self] if @@happy.include?(self) @@happy[self] = false @@happy[self] = self.sosqod.happy? end end [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
Ruby
[QUIZ] Happy Numbers (#93)
Top