码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 7. Reverse Integer

时间:2016-08-05 11:32:00      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:

#include <stdio.h>
#include <math.h>

// 7. Reverse Integer
// Difficulty: Easy
// Reverse digits of an integer.
// Example1: x = 123, return 321
// Example2: x = -123, return -321
// https://leetcode.com/problems/reverse-integer/

int reverse(int x) {

    // *** METHOD 2
    long y = 0;            // a trick, may be improved
    while (x) {
        y = y * 10 + x % 10;
        x /= 10;
        if (y > pow(2,31) - 1 || y < -1 * pow(2,31)) {
            printf("(2^31) - 1 = %d, -1 * (2^31) = %d, y = %ld\n", (int)pow(2,31) - 1, -1 * (int)pow(2,31), y);
            return 0;    // IMPORTANT: consider range of int
        }
    }
    return y;
}

int main() {
    int x = 1534236469;
    printf("x = %d, reversed x = %d\n", x, reverse(x));
    return 0;
}

 

[LeetCode] 7. Reverse Integer

标签:

原文地址:http://www.cnblogs.com/skyssky/p/5740375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!