1. 程式人生 > >LeetCode 之Reverse Integer(C)

LeetCode 之Reverse Integer(C)

Given a 32-bit signed integer, reverse digits of an integer.

給定32位有符號整數,整數的反向數字。

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 which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

程式碼:

#include <stdio.h>
#include <stdlib.h>

int reverse(int x)
{
    long int tmp = x;
    long int value = 0;
    int res = -1;
    while( 0 != res )    // 實現資料反向
        {
            res = x/10;
            value*=10;
            value+=x%10;
            x/=10;
        }
      if(value > 0xffffffff || (((int)tmp > 0) && ((int)value < 0)) || ((int)tmp < 0) && ((int)value > 0)) // 判斷資料合法性
        return 0;
    return (int)value;
}

int main(int argc,int **argv)
{
    int handle = 0;

    if(NULL == argv[1])
        handle=0;
    else
        handle=atoi((char *)argv[1]);
    printf("handle = %d, reverse = %d.\n", handle, reverse(handle));
    return 0;
}