### re: Challenge: find 'Kaprekar numbers' VIEW POST

Here's my Ruby novice solution -- Works for the known oddballs (4879, 5292, 38962). Prepending '0' to odd-sized numbers inspired by others here.

``````def kaprekar?(k)
s = k.to_s.size    # s = nr. of digits in k
k_sq = (k**2).to_s    # k_sq = square of k (String)
k_sq.prepend("0") if (k_sq.size.even? == false)    # prepend '0' to odd-sized numbers
if k_sq[s-1] == "0"    # if digit 's-1' is 0, loop different combinations
(0..s).each do |x|
part1 = k_sq[0..x-1].to_i
part2 = k_sq[x..-1].to_i
return true if (k == part1 + part2)
end
else    # if not, split before digit 's' (Integers)
part1 = k_sq[0..s-1].to_i
part2 = k_sq[s..-1].to_i
return true if k == (part1 + part2)
end
false    # else returns false
end
``````

I don't like the exceptions (4879, 5292, 38962...) -- it feels like they don't belong in the sequence. And look how pretty the code is without them!

``````  def kaprekar?(k)
s = k.to_s.size
k_sq = (k**2).to_s
k_sq.prepend("0") if (k_sq.size.even? == false)
part1 = k_sq[0..s-1].to_i
part2 = k_sq[s..-1].to_i
return true ? k == part1 + part2 : false
end
``````
Code of Conduct Report abuse