IP #6 : Reversing an Integer
Reversing an Integer
by Ashur Baroutta
The focus of this submission will be on reversing a given integer passed into our function. Our problem statement is as follows "Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 -1], then return 0."
Seems simple, though was actually a little odd. My initial reaction is to convert the integer to a string and then just reverse each character. Though in a way that feels like cheating as I don't think that solution is in the spirit of the assignment, and it takes more resources to complete.
Pivoting my attention to a mathematical solution made the problem a lot more fun. Say our first example for x is 123. The way we attack it is to setup variables to track the reversed total and to track the remainder of a given iteration, we also create a loop iterating through while x does not equal 0.
The first thing we do in our loop is track the remainder, if x =123, than we track the remainder of 123%10 (which is 3). Then we divide set x = x/10 so we can continue cutting our integer down in size. After this we set our reversed total to = (reversed*10) plus the remainder.
So in our example, we track our remainder first right, so we have 3. then we reduce 123 in size by dividing by 10, and then we set our reversed (the first iteration being 0) variable to (reverse*10) plus 3, which makes our reverse total now 3. In our second iteration, we do the same, so 12%10 = 2. We now again, reduce 12 by dividing by 10 (left with 1 since we are dividing ints, not doubles or floats). We make reversed = (reversed*10) + remaining (in this iteration 2) for a total of 32. A last iteration does the same workflow and we multiply the 32 by 10 and add the remaining giving us 321!
Definitely a different thought process than the usual problem.
Comments
Post a Comment