zoukankan      html  css  js  c++  java
  • 字符串转化为整数

    题目:

    字符串转换为整数 : atoi

    可能的输入:
    1 带符号数
    2 无符号数
    3 零
    4 空指针
    5 超出表示范围 – 暂时仅仅是直接退出且设置最小 – 可以考虑此时抛个异常
    6 非法输入,比如并不是一个0-9或者+ -组成的字符串 – 对于非法输入一律返回的是Integer.MIN_VALUE

    解答:

     1 public class Solution {
     2 
     3     public static long strToInt(String str) {
     4         if(str == null) {
     5             return Long.MIN_VALUE;
     6         }
     7 
     8         if(str.length() == 0) {
     9             return 0;
    10         }
    11 
    12         for(int i = 0; i < str.length(); i++) {
    13             if(!judge(str.charAt(i))) {
    14                 return Long.MIN_VALUE;
    15             }
    16         }
    17 
    18         char[] chars = str.toCharArray();
    19         long result = 0;
    20 
    21         if(char[0] == '+' || char[0] == '-') {
    22             result = trans(str.substring(1));
    23         } else {
    24             result = trans(str);
    25         }
    26 
    27         if(result > 0 && char[0] == '-') {
    28             result = -result;
    29         }
    30 
    31         return result;
    32     }
    33 
    34     public static boolean judge(char c) {
    35         if(c == '+' || c == '-' || (c >= '0' && c <= '9')) {
    36             return true;
    37         } else {
    38             return false;
    39         }
    40     }
    41 
    42     private static long trans(String str) {
    43         if(str.length() == 0) {
    44             return 0;
    45         }
    46 
    47         long result = 0;
    48         for(int i = 0; i < str.length(); i++) {
    49             result = result*10 + str.charAt(i)-'0';
    50 
    51             // important here
    52             if(result > Long.MAX_VALUE) {
    53                 result = Long.MAX_VALUE;
    54                 break;
    55             }
    56         }
    57 
    58         return result;
    59     }
    60 }

  • 相关阅读:
    导航属性
    提笔忘字
    JavaScript学习总结(一)——闭包、对象、函数
    CSS3新特性(阴影、动画、渐变)
    图片轮播(也可以通过点击下标播放对应的图片)
    CSS3与页面布局学习总结——多种页面布局
    多种居中方法
    二级菜单
    无间隙轮播图片
    模块和程序处理
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10477256.html
Copyright © 2011-2022 走看看