banner
ekko

ekko's blog

时间不在于你拥有多少,而在于你怎样使用
github
xbox
email

Integer Reversal

Description#

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:

Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, if the reversed integer overflows, return 0.

Approach#

  • Extract the sign of the number.
  • Convert the number to a positive number and extract each digit.
  • Reverse the order of the extracted digits and add them up.
  • Check for overflow.
int reverse(int x){
    char sign = 1,nums = 0,value[10] = {0};
    int final = 0;
    long final_long = 0;
    // Extract the sign and digits
    if(x < 0) {
        if(x == -2147483648)//-2^31, cannot be converted to a positive number and will overflow after reversing
            return 0;
        else
            x = -x;
        sign = -1;
    }
    // Get the digits of x
    for(;x;nums++) {
        value[nums] = x % 10;
        x = x / 10;
    }

    for(int i=0;nums > 0;nums--) {
        final_long += value[i++];

        if(nums > 1)//still have next digit
            final_long *= 10;
    }
    final = (int)final_long;
    if(final == final_long)
        return final * sign;
    else
        return 0;
    
}

Note#

  • Error checking includes whether it can be converted to a valid positive number and whether it overflows after reversing.

-------------------------------------------Separator Line!!---------------------------------------

Update#

I saw some other people's solutions online, and I had an epiphany. The above code can be greatly simplified. Here is the updated code:

int reverse(int x){
    int final = 0;
    long final_long = 0;   

    while(x) {
        final_long = final_long * 10 + x % 10;
        x = x / 10;
    }
    final = (int)final_long;
    if(final == final_long)
        return final;
    else
        return 0;
    
}
  1. The extraction of the sign is actually unnecessary because the only difference between positive and negative numbers in the calculation process is the sign of the last digit when taking the modulus. So we can directly perform the calculation without considering the sign. I was too rigid in my thinking and made unnecessary steps.
  2. The calculation of the final result and the extraction of digits can be combined. I used to be fixated on getting the number of digits of the integer before continuing the calculation. However, as shown above, we can simply take the modulus once and then multiply by 10 to continue the process. This really simplifies the process.
  • I didn't realize how much I could learn without directly comparing my solution to others. This problem was not in vain, and I learned a lot from it.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.