zoukankan      html  css  js  c++  java
  • 【leetcode】8.String to Integer (atoi)

    8. String to Integer (atoi)

    Implement atoi to convert a string to an integer.

    Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

    Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

    Tips: 本题要自己实现atoi函数,需要声明的包括:

    ①.java 字符串或者字符数组结尾处并不包含"".

    ②考虑输入的字符串前面有很多空格。

    ③考虑'+','_'

    ④我没通过的case有"    -12a42",正确输出为 -12。

      "2147483648" 正确输出为 2147483647

    package medium;
    
    public class L8StringToInteger_atoi {
    
        public int myAtoi(String str) {
            if (str == "")
                return 0;
            long num = 0;
            int minus = 1;// +
            int i = 0;
            int len = str.length();
            while (i < len) {
                if (str.charAt(i) == ' ') {
                    i++;
                }else{
              break;
           } }
    if (str != null && i < len) { if (str.charAt(i) == '+') { minus = 1; i++; } else if (str.charAt(i) == '-') { minus = -1; i++; } while (i < len) { System.out.println(i + " " + str.charAt(i)); if (str.charAt(i) >= '0' && str.charAt(i) <= '9') { num = num * 10 + minus * (str.charAt(i) - '0'); if ((minus == 1 && num >= 2147483647) ) { num = 2147483647; break; }if( (minus == -1 && num < -2147483648)){ num=-2147483648; break; } i++; System.out.println(i); } else { break; } } } return (int) num; } public static void main(String[] args) { String str = " -0012a42"; L8StringToInteger_atoi l8 = new L8StringToInteger_atoi(); int num = l8.myAtoi(str); System.out.println(num); } }
  • 相关阅读:
    redis内存模型、内存使用的优化
    【转】[Andriod]Xposed和VirtualXposed
    https详解
    http详解
    补码
    浮点数的二进制表示
    Go随机数
    ECDSA--圆锥曲线数字签名算法原理(摘wikepedia)
    Linux命令备忘
    【Windows】系统命令
  • 原文地址:https://www.cnblogs.com/yumiaomiao/p/8407300.html
Copyright © 2011-2022 走看看