leetcode 7. Reverse Integer

来源:互联网 发布:手机淘宝宝贝怎么分类 编辑:程序博客网 时间:2024/06/10 01:05
//Reverse digits of an integer.//Example1: x = 123, return 321//Example2: x = -123, return -321 public class Solution {public static void main(String[] args) {int a =   100;int result = reverse(a);System.out.println(result);} public static int reverse(int x) { int result = 0; String res = ""; String s = Integer.toString(x); boolean flag = false;//第一位是符号还是数字的标志 if(Character.isDigit(s.charAt(0))){//判断第一位是符号还是数字 for(int i = s.length()-1;i>=0;i--){//根据第一位采用不同的操作 res = res+s.charAt(i); } }else{ for(int i = s.length()-1;i>0;i--){ res = res+s.charAt(i); } flag = true;//如果第一位是负号则改变flag } try{ result = Integer.parseInt(res); }catch(Exception e){//如果有数字越界问题,就返回0(题目中没有提到这一点。。。) return 0; } if(flag == true){//根据flag调整结果 result = -result; } return result; }    }

0 0
原创粉丝点击