• 把字符串换成整数


    题目描述

    将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0 
    输入描述:
    输入一个字符串,包括数字字母符号,可以为空
    输出描述:
    如果是合法的数值表达则返回该数字,否则返回0
    输入例子:
    +2147483647
        1a33
    输出例子:
    2147483647
        0
    思路: 数字字符-48等于其本身的数值,如4='4'-48;
    public int StrToInt(String str) {
            if(str.equals("0")||str==null||str.length()==0) return 0;
            else{
                char beg = str.charAt(0);
                int m=0;
                if(beg=='+'||beg=='-'){
                    m = getInt(str,1,str.length()-1);
                    if(beg=='+') return m;
                    else if(beg=='-') return -(m);
                }else if(String.valueOf(beg).matches("[1-9]")){
                    m=getInt(str,0,str.length()-1);
                    return m;
                }
                return 0;
            }
        }
        public int getInt(String str,int begin,int end){
            int m=0;
            for(int i=begin;i<str.length();i++){
                char c = str.charAt(i);
                if(String.valueOf(c).matches("[0-9]")){
                    m=m*10+ c-48; //确保算出来的结果。
                }else{
                    return 0;
                }
            }
            return m;
        }
  • 相关阅读:
    ShellExecuteEx 函数说明
    npm
    Byte和char
    如何高效阅读一个项目
    C++中慎用malloc
    #ifdef
    string
    C++与C混合编译
    git@github.com: Permission denied (publickey).
    connect to host github.com port 22: Connection refused
  • 原文地址:https://www.cnblogs.com/yingpu/p/5832605.html
Copyright © 2020-2023  润新知