Reverse Integer

来源:互联网 发布:果园拆分系统源码 编辑:程序博客网 时间:2024/06/05 14:53

my solution:

/** * 2017年4月18日21:04:16 * ------------------------------------------------------ * 本程序的问题描述: *   Example1: x = 123, return 321 *   Example2: x = -123, return -321 *    *   The input is assumed to be a 32-bit signed integer.  *   Your function should return 0 when the reversed integer  *   overflows. *------------------------------------------------------ * 在本程序中我所面临的问题有: *   如果输入的数字的最后一位是0怎么办? *   借鉴的别人的程序里面的 INT_MIN INT_MAX 是怎么回事? *   对于溢出还是没有理解. * ------------------------------------------------------ * 本程序所带来的延伸或者我的思考或者程序中的重点有: *   自己写的程序太麻烦了. */#include <iostream>#include <math.h>using namespace std;int len(int n){       int i = 1;    while((n / 10) >= 1)    {        i++;        n = n / 10;    }    return i;}int abs(int n){    n = -n;    return n;}int Reverse(int n){       int nLen = len(n);    int num;    for(int i=0; i<nLen; i++)    {        num = (int)(n / pow(10,i)) % 10;        cout << num;    }}int main(){       int n;    cin >> n;    if(n < 0)    {        n = abs(n);        cout << "-";        Reverse(n);    }    else    {        Reverse(n);    }}

other’s:

#include <stdio.h>int reverse(int x){    long long val = 0;    do    {        val = val*10 + x%10;        x /= 10;    }while(x);    return (val > INT_MAX || val < INT_MIX) ? 0 : val;}

other’s:

/** * long long make res a 64 bit number, the overflow is  checked. */class Solution {public:    int reverse(int x) {        long long res = 0;        while(x) {            res = res*10 + x%10;            x /= 10;        }        return (res<INT_MIN || res>INT_MAX) ? 0 : res;    }};
0 0