zoukankan      html  css  js  c++  java
  • 8. String to Integer (atoi)

    8. String to Integer (atoi)

     
     
    Total Accepted: 97070 Total Submissions: 721266 Difficulty: Easy

    Implement atoi to convert a string to an integer.

    Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

    Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

    Update (2015-02-10):
    The signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.

    Code:

    int myAtoi(char* str) {
        if(!str)
            return 0;
        int sign = 1;
        int num = 0;
        while(*str == ' ')
            str++;
        if(*str == '+')
            str++;
        else if(*str == '-')
        {
            sign = -1;
            str++;
        }
        while(*str!='')
        {
            if(*str == '+'||*str == '-')
                return 0;
            else if(*str<'0'||*str>'9')
                return num*sign;  
            if (num > INT_MAX / 10)   
                    return sign == 1? INT_MAX : INT_MIN;  
                num*=10;
            if ((*str - '0') > (INT_MAX - num))   
                    return sign == 1? INT_MAX : INT_MIN;   
            num = num + *str - '0';  
            str++;
        }
        return num*sign;
    }

  • 相关阅读:
    如何快速开发一个自己的项目脚手架?
    Vue模板语法中数据绑定
    vue组件间通信八种方式
    浏览器渲染页面流程
    双飞翼布局
    单行截断和多行截断问题
    flex 布局实现固定头部和底部,中间滚动布局
    defer 和 async 区别
    数学之美(统计语言模型)
    react 源码之setState
  • 原文地址:https://www.cnblogs.com/Alex0111/p/5382991.html
Copyright © 2011-2022 走看看