7. Reverse Integer

来源:互联网 发布:自学网络编程 编辑:程序博客网 时间:2024/05/22 19:10

题目描述

Reverse digits of an integer.

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

思路

一开始想的比较简单,直接循环取尾数*10。

#include<iostream>using namespace std;int main(){    int n, count = 0;    int digit = 0;    cin>>n;    while(n  != 0)    {        count = n % 10;        digit = digit*10 + count;        n = n / 10;    }    cout<<digit;    return 0;}

但是int会溢出比如1000000009 本应该变为 9000000001这个是溢出,题目要求应该是0,但是实际输出会变为一个其他的数,因此在范围外给他设为0.

class Solution {public:    int reverse(int n) {    int count = 0;    long long digit = 0;    while(n  != 0)    {        count = n % 10;        digit = digit*10 + count;        n = n / 10;    }    if(digit > 2147483647 || digit < -2147483648)    return 0;    return digit;    }};
0 0
原创粉丝点击