LeetCode_Reverse Integer

Reverse digits of an integer.



Example1: x = 123, return 321

Example2: x = -123, return -321
class Solution {

public:

    int reverse(int x) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if(x == 0) return x;

        int flag = 1;

        

        if(x < 0)

        {

            x*= -1;

            flag = -1;

        }

        vector<int> result;

        while(x)

        {

          int temp = x %10;

          result.push_back(temp);

          x/=10;

        }

        int num = 0;

        for(int i = 0; i< result.size(); i++)

        {

                num +=result[i];

                num*=10;

        }

        

        return flag*num/10 ;

    }

};

 

你可能感兴趣的:(LeetCode)