zoukankan      html  css  js  c++  java
  • 把字符串转换成整数

    将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0 

    输入一个字符串,包括数字字母符号,可以为空,
    如果是合法的数值表达则返回该数字,否则返回0
    in:
    +2147483647
        1a33
    out:
    2147483647
        0
    public class Solution {
        public int StrToInt(String str) {
            if (str == null || str.equals("0") ||str.equals(""))
                return 0;
            boolean isPositive = true;
            if (str.charAt(0) == '+') {
                isPositive = true;
                str = str.substring(1);
            }
            else if (str.charAt(0) == '-') {
                isPositive = false;
                str = str.substring(1);
            }
            else {
                isPositive = true;
            }
             
            int ans = 0;
            int ary = 1;
            for (int i=str.length()-1; i>=0; i--) {
                if (!isDigit(str.charAt(i))) {
                    return 0;
                }
                ans += ary * (str.charAt(i)-'0');
                ary *= 10;
            }
                 
            ans = isPositive ? ans : -ans;
            return ans;
             
        }
         
        public boolean isDigit(char ch) {
            if (ch < '0' || ch > '9')
                return false;
            return true;
        }
    }
  • 相关阅读:
    Scrapy-02-item管道、shell、选择器
    django类视图的装饰器验证
    django禁用csrf
    django admin
    关系型数据库与非关系型数据库
    LINQ.CS
    测试
    测试
    一个测试
    WPF中的Style
  • 原文地址:https://www.cnblogs.com/wxisme/p/5832861.html
Copyright © 2011-2022 走看看