LeetCode No.7 Reverse Integer

来源:互联网 发布:ubuntu 文件夹root权限 编辑:程序博客网 时间:2024/05/16 09:10

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

====================================================================================

题目链接:https://leetcode.com/problems/reverse-integer/

题目大意:求一个整数的逆序整数(如题)。

思路:每次取x的最后一位放入ans的最后一位。

注意点:当结果越界时,返回0

附上代码:

class Solution {public:    int reverse(int x) {        int ans = 0 ;        while ( x )        {            int tans = ans * 10 + x % 10 ;            x /= 10 ;            if ( tans / 10 != ans )//如果越界,则返回0            {                ans = 0 ;                break ;            }            ans = tans ;        }        return ans ;    }};


0 0
原创粉丝点击