• 【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

  • 相关阅读:
    group by 详解
    NHibernte教程(10)--关联查询
    NHibernate教程(9)一1对n关联映射
    NHibernate教程(8)--巧用组件
    NHibernate教程(7)--并发控制
    Git初步配置 ubuntu服务器 windows客户端 虚拟机
    设计模式之GOF23状态模式
    设计模式之GOF23模板模式
    设计模式之GOF23策略
    设计模式之GOF23访问者模式
  • 原文地址:https://www.cnblogs.com/haoworld/p/offer67-ba-zi-fu-chuan-zhuan-huan-cheng-zheng-shu.html
Copyright © 2020-2023  润新知