zoukankan      html  css  js  c++  java
  • 剑指Offer(Java版)第五十五题:将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0。

    /*
    将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。
    数值为0或者字符串不是一个合法的数值则返回0
    */
    //输入一个字符串,包括数字字母符号,可以为空
    //如果是合法的数值表达则返回该数字,否则返回0
    //输入:
    //+2147483647
    //1a33
    //输出:
    //2147483647
    //0
    public class Class55 {

    public int StrToInt(String str){
    if(str == null || str.length() == 0 || str == " "){
    return 0;
    }
    char[] ch = str.toCharArray();
    int index = 0;
    int i = 0;
    if(ch[0] == '+'){
    index = 1;
    i = 1;
    }
    if(ch[0] == '-'){
    index = -1;
    i = 1;
    }
    int sum = 0;
    for(; i < ch.length; i++){
    if(ch[i] >= 48 && ch[i] <= 57){ //ASCII码
    sum = sum * 10 + ch[i] - 48;
    }else{
    return 0;
    }
    }
    if(index == 1){
    return sum;
    }
    if(index == -1){
    return sum = sum * (-1);
    }
    return sum;
    }

    public void test(){
    String str = "-2147483647";
    System.out.println(StrToInt(str));
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Class55 c = new Class55();
    c.test();

    }

    }

  • 相关阅读:
    Dapper 基础用法
    测试的分类
    Python
    MySQL数据库的增删改查
    Python面向对象之
    Python面向对象之
    Python
    HTML5/CSS3/JS笔记
    Python-Flask框架之
    Python进程与线程
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12535472.html
Copyright © 2011-2022 走看看