zoukankan      html  css  js  c++  java
  • leetcode08--String to Integer(实现字符串到整数的转换)

    实现字符串到整数的转换

    注意事项:

    下面给出这道题应该注意的一些细节:

    1. 字符串“ 123 ” = 123;

    2. 字符串“+123” = 123;

    3. 字符串“-123” = -123;

    4. 字符串“-” = 0;“+” = 0;

    5. 字符串“123-” = 123;

    6. 字符串“21474836478” = 2147483647(Integer.MAX_VALUE)

    7. 其余情况都是非法输入,一律返回0;*/
     1 public class Main05 {
     2     public static void main(String[] args) {
     3         Scanner scan = new Scanner(System.in);
     4         while (scan.hasNext()){
     5             String str = scan.nextLine();
     6             System.out.println(atoi(str));
     7 
     8         }
     9     }
    10 
    11     private static int atoi(String str) {
    12         if(str == null || str.trim().length() ==0){
    13             return 0;
    14         }
    15         str = str.trim();
    16         String res = "";
    17         int index = 0;
    18         String minStr = "";
    19         if(str.charAt(0) =='-'){
    20             minStr = "-";
    21             index++;
    22         }else if(str.charAt(0) =='+'){
    23 
    24             index++;
    25         }
    26         for(int i=index;i<str.length();i++){
    27             if(str.charAt(i)>='0' && str.charAt(i)<='9'){
    28                 res +=str.charAt(i);
    29             }else {
    30                 break;
    31             }
    32         }
    33         if(res == ""){
    34             return 0;
    35         }
    36         if(Long.valueOf(minStr+res)>Integer.MAX_VALUE){
    37             return Integer.MAX_VALUE;
    38         }
    39         if(Long.valueOf(minStr+res)<Integer.MIN_VALUE){
    40             return Integer.MIN_VALUE;
    41         }
    42 
    43         return Integer.valueOf(minStr+res);
    44     }
    45 
    46 }


  • 相关阅读:
    【提高组】
    【学习】数论
    【2019.10.2】NOIP2018 模拟赛
    【普及组BOSS】
    ELK搭建elasticsearch常见报错
    Linux 下 安装Python第三方模块工具箱pip,以及用pip安装的方法
    Centos 基本命令不能用恢复方法
    Docker0 网卡删除
    Tomcat 设置开机自启
    Python 终端输出字体颜色
  • 原文地址:https://www.cnblogs.com/huststl/p/8732692.html
Copyright © 2011-2022 走看看