Given a 32-bit signed integer, reverse digits of an integer.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
==Example==
123→321 -123→-321 120→21
第一时间想到这是经典的取模取余运算,可是写的过程当中遇到了不少问题QAQ(这么简单一题git
用这个方法最大的难点在于用int类型时处理溢出问题,本来没有溢出的数字在进行翻转时颇有可能溢出,最合适的方法是在处理过程当中进行预判函数
Java代码:this
public static int reverse(int x) { int overFlow = (int)Math.pow(2,31) -1; //overFlow = 2147483646 int underFlow = 0 - (int)Math.pow(2,31); //underFlow = -2147483647 int pop = 0; int result = 0; while(x != 0){ pop = x % 10; if((result>overFlow/10) || (result==overFlow/10 && pop>7)) return 0; if((result<underFlow/10) || (result==underFlow/10 && pop<-8)) return 0; result = result * 10 + pop; //★ x = x/10; } return result; }
题目中要求的溢出条件实际上是针对int型数据的,这题用Java来写的话其实能够用long类型code
Java代码:ip
public int reverse(int x) { long res = 0; //此处用了long while (x != 0) { res = res * 10 + x % 10; x = x / 10; } return (int)res == res ? (int)res : 0; }