Leetcode-整数反転C++

1015 ワード

タイトル:32ビットのシンボル付き整数を与え、この整数の各ビットの数字を反転する必要があります.例1:入力:123出力:321例2:入力:-123出力:-321例3:入力:120出力:21
考え方:入力された数字xを1つずつ文字列タイプに変換します.例えばx=123をstrX=321に変換し、最後に文字列タイプの数字を整形に戻し、プラスとマイナスの補完を加えます.実は数字->文字列のステップを省いて、直接数字の回転を行うことができます.
コード:
class Solution {
public:
    int reverse(int x)
{
    long max=2147483647;//         ,    
    long min=-2147483648;
    if (x < 10 && x > -10)//   10         
        return x;
    bool neg=false;//    x     

    if (x < 0)
    {
        neg = true;
        x *= -1;
    }
    int tmp = x;
    string rev;
    while (tmp != 0)
    {   //int to string
        //243 to 342
        rev += (tmp - tmp / 10 * 10);
        tmp = tmp / 10;
    }
    long reved = 0;
    for (int i = 0; i < rev.length(); ++i)
    { //342 to 243
        reved += rev.data()[i];
        reved *= 10;
    }
    reved = reved / 10;
    if (reved >= max || reved <= min)
        return 0;
    if (neg == true)
        reved *= -1;

    return reved;
}
};