leetcode #7 ReverseInteger

来源:互联网 发布:生男生女预测表49算法 编辑:程序博客网 时间:2024/05/16 03:05

采用了一个不过脑子的算法,只是因为写的快。。。不能这样了

public class Solution {    public int reverse(int x) {      int fin=0;        boolean negative;        if(x>=0)negative=false;        else negative=true;        x=Math.abs(x);        StringBuffer tmp = new StringBuffer(String.valueOf(x));        tmp.reverse();              if(negative)tmp.insert(0,'-');        try{            fin = Integer.parseInt(tmp.toString());        }catch(NumberFormatException e){            System.out.println("number out of range!");         }finally{            return fin;         }            }}

欠考虑了int翻转之后溢出的情况,发现之后完成修改。
所以这个代码有待完善

Fignt On!

Update

public class Solution {    public int reverse(int x) {        int fin=0,digit=0;        boolean negative=(x>=0)?false:true;        if(negative)x=0-x;        while(x!=0){    digit=x%10;        x=x/10;         fin=fin*10+digit;                   }        if(negative)fin=0-fin;        return fin;     }}

OK

0 0
原创粉丝点击