zoukankan      html  css  js  c++  java
  • (atoi)String to Integer 49

    corner case的处理

       

    整数一般考虑两点:一点是符号,另外一点是越界

       

    首先去掉多余的空格字符

       

    然后读符号,可能是正号,也可能是负号,也可能没有符号

       

    然后按顺序读数字

       

    结束条件有三:

    1、异常字符出现——舍弃异常字符后的数据,保留前面的数作为结果;

    2、数字越界——返回最接近的整数;

    3、正常结束

       

    长度为0,返回0

       

    输入0,返回0,但有个finished,如果为true,则是输入0,如果为false,则是长度0,如果直接是异常字符,那么还是返回0,此时finishedfalse

       

       

    package stringToInt49;

       

    public class StringToInt49 {

    static boolean finished = false;

    public int atoi(String str) {

    int length = str.length();

    if (length == 0)

    return 0;

    int i = 0;

    boolean minus = false;

    if (str.charAt(0) == '-') {

    minus = true;

    i++;

    } else if (str.charAt(0) == '+') {

    i++;

    }

    long MIN_VALUE = Integer.MIN_VALUE;

    long MAX_VALUE = Integer.MAX_VALUE;

    long num = 0;

       

    for (; i < length && !finished; i++) {

    char c = str.charAt(i);

    if (c >= '0' && c <= '9') {

    num *= 10;

    num += c - '0';

    } else {

    num=0;

    break;

    }

       

    if (minus && 0 - num < MIN_VALUE) {

    return Integer.MIN_VALUE;

    }

    if (!minus && num > MAX_VALUE) {

    return Integer.MAX_VALUE;

    }

    }

    if (i==length) {

    finished = true;

    }

    return minus ? new Long(0 - num).intValue() : new Long(num).intValue();

    }

    public static void main(String[] args) {

    StringToInt49 stringToInt49=new StringToInt49();

    System.out.println(stringToInt49.atoi("123"));

    }

    }

       

  • 相关阅读:
    暑假第二周总结
    7.18-7.24 第一周周报
    poj 3295 Tautology
    2016多校 #2 1006 Fantasia
    codeforces 698B Fix a Tree
    codeforces 699B Bomb
    HDU 4578(线段树
    CF 600F( 二分图
    hdu 5517 Triple(二维树状数组)
    HDU HDOJ5412(树套树or整体二分
  • 原文地址:https://www.cnblogs.com/keedor/p/4378928.html
Copyright © 2011-2022 走看看