Given a 32-bit signed integer, we want to generate the 32-bit signed integer obtained by reversing the digits of the original number. Incase, the result is beyond the range of a 32-bit signed integer, we return 0. To reverse a number we need to progressively extract the mod 10 and keep pushing into our new by first multiplying it by 10 and then adding the obtained digit from the original number. This is equivalent to extracting the digit, right shifting the given number, left shifting the new number and adding the digit. class Solution { public int reverse(int x) { long soln = 0; while(x != 0) { soln = 10 * soln + x % 10; x /= 10; } if ((soln > Integer.MAX_VALUE) || (soln < Integer.MIN_VALUE)) return 0; return (int)soln; } } The above code uses the constants from Integer class in java.lang package. However, this logic fails if we are given a 64-bit signed number, as we will not hav...



Nice Blog
ReplyDeleteMMT Sharjah
MMT
Maria Medical Technology
Maria Medical Technology Sharjah
Maria Medical Technology UAE
Artificial Intelligence in Sharjah
Artificial Intelligence
Robotics in Sharjah
Robotic ARM in Sharjah