leetcode-7.整数反转

leetcode-7.整数反转

idea:题面是将给定32以内整数反转

算法:先判断数字正负,记录符号(1 / -1)

   将数字每一位用数组存储

     遍历数组,通过权重不同实现数字反转,过程中判断是否超出32位数字范围(2147483647 ~ -2147483648),超出直接返回0

   返回计算结果与符号的乘积

code:

注意:做边界值的检测

class Solution {
public:
    int reverse(int x) {
        int a[100];
        int index = 0;//数组索引(下标)
        int signal = 1;
        if(x < 0)//判断一下正负
        {
            signal = -1;
            x = -x;
        }
        while(x)//数字数组化
        {
            a[index] = x % 10;
            x /= 10;
            index++;
        }
        x = 0;
        for(int i = 0; i < index; i++)//反转计算
        {
            x += a[i]*pow(10, index-i-1);
            if(x >= 2147483647 || x < -2147483647)//做32位数字边界判断,超出返回0
            {
                return 0;
            }
        }
        return x*signal;
    }
};

     

原文地址:https://www.cnblogs.com/yocichen/p/10217348.html