zoukankan      html  css  js  c++  java
  • Leetcode7>Reverse Integer(逆转整数)

    题目: 给定一个整数,求将该整数逆转之后的值;

    举例:

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

    解题思路:

    在这里只用说明几个要注意的点:

    1.  如果该整数是负数,-123,则逆转之后为-321,因此需要从第一位开始逆转,而不是第0位;

    2.  如果整数例如:12300,则逆转后为321,而不是00321,因此逆转后,需要去除前面的0;

    3.  如果整数例如:2147483647,则逆转后为7463847412 > Integer.MAX_VALUE,则返回0;

     1 public class Solution {
     2     public int reverse(int x) {
     3         char[] ch = String.valueOf(x).toCharArray();
     4         int begin = 0;
     5         int flag = 0; // flag用来表示是正数还是负数
     6         int end = ch.length - 1;
     7         if(x < 0){  // 负数
     8             flag = 1;
     9         }
    10         begin = flag;
    11         while(begin < end){
    12             exchange(ch, begin, end);
    13             begin ++;
    14             end --;
    15         }
    16         StringBuffer sb = new StringBuffer();
    17         int i = flag;
           // 去掉逆转后前面的0
    18 for(; i < ch.length; i++){ 19 if(ch[i] != '0') 20 break; 21 } 22 if(flag == 1) 23 sb.append("-"); 24 sb.append(ch, i, ch.length - i); 25 if(sb.toString().equals("")) 26 return 0; 27 double res = Double.valueOf(sb.toString()); 28 if(res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) 29 return 0; 30 return Integer.valueOf(sb.toString()); 31 32 33 } 34 public void exchange(char[] ch, int index1, int index2){ 35 char c = ch[index1]; 36 ch[index1] = ch[index2]; 37 ch[index2] = c; 38 } 39 }
  • 相关阅读:
    asp.net core 3.1 源码学习(二)
    asp.net core 3.1 源码学习(一)
    netcore3.0 IHost 源码解析(二)
    netcore3.0 IHost 源码解析(一)
    netcore3.0 Logging 日志系统(三)
    netcore3.0 Logging 日志系统(二)
    netcore3.0 Logging 日志系统(一)
    netcore3.0 IOptions 选项(二)
    Nginx使用记录
    SC Create 创建一个Windows系统服务 转
  • 原文地址:https://www.cnblogs.com/leavescy/p/5878655.html
Copyright © 2011-2022 走看看