bigevil的专栏

Reverse Integer

Reverse digits of an integer.

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

这题比较容易,就是把给的一个数,反顺序输出而已。

直接对10取余数,把每一位数字读出来,再生成一个新的数就可以了,边界有一个溢出的问题,在这里,我选择的方法是定义一个long类型的变量,该变量与新生成的数赋值方法一样。然后检查这个long类型的变量是否与int类型变量的值相等就好了。

public static int reverse(int x) {int temp = 0;int res = 0;long testres = 0;while (x!=0) {temp = x%10;x = x/10;res = res*10 + temp;testres = testres*10 + temp;}if (res!=testres) {return 0;}return res;}

,要想捉大鱼,不能怕水深。要想摘玫瑰,就得不怕刺。

bigevil的专栏

相关文章:

你感兴趣的文章:

标签云: