牛客网刷题之把字符串转换成整数

来源:互联网 发布:我的第一本编程书 编辑:程序博客网 时间:2024/04/26 18:36

题目描述:

这里写图片描述
这里写图片描述

解题思路:

  首先要判断字符串是否有效,如果为空就直接返回false即可,如果是非空就判断是否含有非数字字符。需要注意的是:字符串首字符为“+”和“-”的情况。接着就是正常计算了,以”345”作为例子。当我们扫描到字符串的第一个字符’3’时,我们不知道后面还有多少位,仅仅知道这是第一位,因此此时得到的数字是3。当扫描到第二个数字’4’时,此时我们已经知道前面已经一个3了,再在后面加上一个数字4,那前面的3相当于30,因此得到的数字是3*10+4=34。接着我们又扫描到字符’5’,我们已经知道了’5’的前面已经有了34,由于后面要加上一个5,前面的34就相当于340了,因此得到的数字就是34*10+5=345。因此,计算思路是,每扫描一个字符,将之前得到的结果乘以10加上当前扫描字符表示的数字。

题解:

    public int StrToInt(String str) {        if ("".equals(str)) {            return 0;        }        int result = 0;        if (str.charAt(0) == '-' || str.charAt(0) == '+') {            for (int i = 1; i < str.length(); i++) {                if (str.charAt(i) < '0' || str.charAt(i) > '9') {                    return 0;                }                result = result * 10 + (str.charAt(i) - '0');            }            if (str.charAt(0) == '-') {                result = 0 - result;            }        } else {            for (int i = 0; i < str.length(); i++) {                if (str.charAt(i) < '0' || str.charAt(i) > '9') {                    return 0;                }                result = result * 10 + (str.charAt(i) - '0');            }        }        return result;    }

ac结果:

这里写图片描述

0 0
原创粉丝点击