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

    题目描述

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

    输入描述:

    输入一个字符串,包括数字字母符号,可以为空

    输出描述:

    如果是合法的数值表达则返回该数字,否则返回0
    示例1

    输入

    +2147483647
        1a33

    输出

    2147483647
        0

    public class Solution {
        public int StrToInt(String str) {
            char[] ch = str.toCharArray();
            int s = 1;
            long sum = 0;
            if(ch.length == 0)return 0;
            if(ch[0] == '-') s = -1;
            for(int i = (ch[0]=='+' || ch[0]=='-')?1:0; i < ch.length; i++) {
                if(ch[i]>='0' && ch[i]<='9'){
                    sum = sum * 10 + ch[i]-'0';
                }else{
                    return 0;
                }
            }
            sum = sum * s;
            return (int)sum;
        }
    }
  • 相关阅读:
    js练习题2
    js样式
    js小练习
    css动画样式
    css盒子、布局样式
    css一般样式
    css样式、选择器
    html表格、表单
    html 标签
    mysql连接查询,子查询,联合查询
  • 原文地址:https://www.cnblogs.com/yihangZhou/p/10500582.html
Copyright © 2011-2022 走看看