7. reverse integer

    xiaoxiao2021-03-25  130

    Reverse digits of an integer.

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

    click to show spoilers.

    Note: The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.

    Subscribe to see which companies asked this question.

    思路:借助%和/操作,注意当翻转结果越界时要返回零

    public int reverse(int x) { if(x==0) return 0; int y=x; long out=0;//long型是为判断是否整型越界 while(y!=0){ out=out*10+(y);// y=y/10; //System.out.print(out+"\t"); if(out>Integer.MAX_VALUE||out<Integer.MIN_VALUE) return 0; } return (int)out; }

    转载请注明原文地址: https://ju.6miu.com/read-7040.html

    最新回复(0)