• 把字符串转换成整数


    题目描述:将一个字符串转换成一个整数(实现Integer.valueOf(string)的功能,但是string不符合数字要求时返回0),要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

    思路分析:要把字符串转换为整数主要考虑以下几种情况:

    代码实现

    public class Solution {
       public int StrToInt(String str) {
     
            if (str == null || str.length() == 0 || hasNonNumerical(str)) {
                // 如果字符串为空并且包含非数字字符
                return 0;
            }
     
            // 此时的字符串肯定是数字字符串
            // 因为返回值限定为int型,所以无需考虑大数问题
            char firstChar = str.charAt(0);
            // 先将除第一位的数字转换成整数
            int sumExcludeFirst = 0;
            int sum = 0;
            for (int i = 1; i < str.length(); i++) {
                // 拿出当前字符
                char c = str.charAt(i);
                // 将当前字符转换为整数
                int convert = c - '0';
     
                if (firstChar == '+' && sum <= Integer.MAX_VALUE) {
                    sum += convert * Math.pow(10, str.length() - 1 - i);
                } 
     
                if (firstChar == '-' && sum >= Integer.MIN_VALUE) {
                    sum -= convert * Math.pow(10, str.length() - 1 - i);
                }
     
                if (firstChar >= '0' && firstChar <= '9' && sum <= Integer.MAX_VALUE) {
                    sum += convert * Math.pow(10, str.length() - 1 - i);
                }
     
            }
            
     
            int first = firstChar - '0';
            if (firstChar >= '0' && firstChar <= '9') {
                sum += first * Math.pow(10, str.length() - 1);
            }
            
            if (sum > Integer.MAX_VALUE || sum < Integer.MIN_VALUE) {
                return 0;
            }
            return sum;
     
        }
     
        // 判断一个字符串除第一个字符外是否包含非数字字符,第一个字符可以是+或者是—
        private boolean hasNonNumerical(String str) {
     
            int length = str.length();
     
            // 取出第0位,若第0位如果是数字或者是+,—则继续遍历,否则直接返回false
            char c = str.charAt(0);
            if ((c >= '0' && c <= '9') || (c == '+') || (c == '-')) {
                // 有必要进行之后的遍历
                for (int i = 1; i < length; i++) {
                    // 取出当前字符
                    c = str.charAt(i);
                    if (c < '0' || c > '9') {
                        // 证明包含非数字字符,直接跳出循环,返回false
                        return true;
                    }
                }
     
            } else {
                // 首位就包含除正负号外的非数字字符
                return true;
            }
     
            return false;
        }
    }
  • 相关阅读:
    jquery ajax get 数组参数
    xcopy中文文件名,中文件目录乱码问题
    小程序使用wxParse插件解析html标签图片间距问题
    30分钟彻底弄懂flex布局
    abp ueditor 多图以及文件无法上传
    Lubuntu 18.04 自动登录
    树莓派虚拟环境手动安装HA
    ESP-01S刷ESPEasy固件,接入HA
    百度TTS的来由
    Pi 3B+编译安装python3.6.8
  • 原文地址:https://www.cnblogs.com/Dream-chasingGirl/p/10302809.html
Copyright © 2020-2023  润新知