zoukankan      html  css  js  c++  java
  • 【Offer】[67] 【把字符串转换成整数】

    题目描述

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

    牛客网刷题地址

    思路分析

      要注意特殊情况:null、空字符串、带有正负号、字符不是数字、溢出等等。
    对于非法的特殊输入,返回值为0,还要用一个全局变量进行标记。

    测试用例

    1. 功能测试:正、负、零、带有正负号的数字。
    2. 边界值测试:最大正整数,最小负整数。
    3. 特殊测试:null,数空字符串,仅有正负号,非法字符

    Java代码

    public class Offer067 {
        public static void main(String[] args) {
            test1();
            test2();
            test3();
            
        }
    
        public static int StrToInt(String str) {
            return Solution1(str);
        }
    
         static boolean isValid = false;
    
        private static int Solution1(String str) {
            if(str == null || str.length()<=0)
                return 0;
            char[] chars = str.toCharArray();
            long num=0;  //先用long来存储,以防止越界
            boolean minus=false;
            for(int i=0; i<chars.length; i++){
                if(i==0 && chars[i]=='-'){
                    minus=true;
                }else if(i==0 && chars[i]=='+'){
                    minus=false;
                }else{
                    int a=(int) (chars[i]-'0');
                    if(a<0 || a>9){
                        isValid=false;
                        return 0;
                    }
                    num= (minus==false) ? num*10+a : num*10-a;
                    isValid=true;  //不放在最后面是为了防止str=‘+’的情况被判断为true
                    if((!minus && num>0x7FFFFFFF)
                       ||(minus && num<0x80000000)){
                        isValid=false;
                        return 0;
                    }
                }
            }
            return (int)num;
        }
    
        private static void test1() {
    
        }
    
        private static void test2() {
    
        }
        private static void test3() {
    
        }
    
    }
    

    代码链接

    剑指Offer代码-Java

  • 相关阅读:
    Tomcat原理与实践
    Spring Boot入门与实践
    Docker安装及使用
    JDK源码解析——集合(一)数组 ArrayList
    浅谈mysql底层索引
    微信小程序全局配置知识点
    uniapp全屏高度
    npm node-sass报错
    微信小程序接口配置问题
    微信小程序的设计流程
  • 原文地址:https://www.cnblogs.com/haoworld/p/offer67-ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu.html
Copyright © 2011-2022 走看看