10期学员第一次面试笔试题之一

/*
    写一个函数,用于检测一个32位的有符号整数反转后是否溢出,如果有则返回0,否则返回反转后的值,
    如:123--321  -123 -- -321  1563847412 -- 0  0 -- 0
*/
#define     _CRT_SECURE_NO_WARNINGS
#include    
#include    
#include    
using namespace std;

int checkAndReverse(int num)
{
    long long   n1 = 0,n2 = 0;
    int         symbol = num > 0 ? 1 : -1;
    char        s1[12] = { '\0' }, s2[12] = {'\0'};
    sprintf(s1, "%lld", (long long)num * symbol);
    sprintf(s2, "%lld", num > 0 ? (long long)INT_MAX : (long long)INT_MIN * symbol);
    _strrev(s1);
    cout << "反转值:" << s1 << endl << "极限值:" << s2 << endl;
    n1 = atoll(s1), n2 = atoll(s2);
    return (n1 < n2) ? (int)s1 * symbol : 0;
}


int main()
{
    int num = 1563847412;  //2147483647  -2147483648
    int result = checkAndReverse(num);
    if (result == 0 && num != 0)
    {
        cout << "数据反转后越界" << endl;  
    }
    else
    {
        cout << "未越界,反转后的结果:" << result << endl;
    }
    getchar();
    return 1;
}

你可能感兴趣的:(云创动力)