Split An Integer in Half Using Ruby : Divmod Method

Last night I was completing the first daily challenge for HackerRank’s Week 34 Coding Challenge. At one point during the exercise, I needed to split an integer in half using Ruby, and then find the sum of each half’s individual digits.

For example, I needed the number :

123456

to become instead :

123 and  456

so that I could do :

1 + 2 + 3 = 6

and

4 + 5 + 6 = 15

I accomplished this was using Ruby’s divmod method, since using divmod(1000) on a  6 digit integer would conveniently result in the following array :

x = 123456

x.divmod(1000)

=> [123, 456]

Split An Integer In Half Using Ruby Divmod

After finishing the challenge, I ended up writing a function that can take any sized integer, and splits it in two, returning an array that has two values. This is easily accomplished using the little trick with Ruby’s built in divmod method :

For more information about using divmod, please check out the official Ruby documentation, which can explain the behavior of this method much better than I can : https://ruby-doc.org/core-1.9.3/Numeric.html#divmod-method

 

Leave a Reply

Your email address will not be published. Required fields are marked *