土法整数反转

class Solution {

    public int reverse(int x) {

        String str = x + "";

        StringBuffer resBuffer = new StringBuffer(32);

        StringBuffer strBuffer = new StringBuffer(str);

        char charArray [] = strBuffer.toString().toCharArray();

        int add = 0;

        for (int i = 0; i<charArray.length; i++) {

           char c = charArray[i];


           if (c == '-' && i == 0) {

                resBuffer.append(c);

                add = 0;

                continue;

            } else if (c != '-' && i == 0) {

                add = 1;

            }

            int index = charArray.length-i-add;

            char str1 = charArray[index];

            String tempStr = resBuffer.toString();

            if (tempStr.contains("-")) {

                tempStr = tempStr.substring(0, 0) + tempStr.substring(1);

            }

            Integer tempInteger;

            int tempInt = 0;

            if (tempStr.length()!=0) {

                Double tempDouble = Double.parseDouble(tempStr);

                tempInt = tempDouble.intValue();

            }

            if (str1 == '0' && charArray.length>1 && tempInt == 0) {

                continue;

            } else {

                resBuffer.append(str1);

            }

        }

        String resStr = resBuffer.toString();

        long l = Long.parseLong(resStr);

        if (l <= Math.pow(-2, 31) || l >= Math.pow(2, 31) - 1){//如果溢出,则将结果设为0,跳出循环。

            l=0;

        }

        return (int)l;

    }

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容