博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 8:String to Integer (atoi)
阅读量:4150 次
发布时间:2019-05-25

本文共 2111 字,大约阅读时间需要 7 分钟。

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.

代码如下:

class Solution {public:    long strtol(const char *nptr, char **endptr, int base)		{			const char * s;			long acc, cutoff;			int neg, any, cutlim;			int c;			if (base<0 || base==1 || base>36)			{				if (endptr!=0)					*endptr = (char*)nptr;				return 0;							}			s = nptr;			do 			{				c = (unsigned char) *s++;			} while(isspace(c));			if (c == '-')			{				neg = 1;				c = *s++;			} 			else			{				neg = 0;				if ( c=='+')					c = *s++;			}			if ((base==0 || base==16) &&c=='0' &&(*s =='x' || *s == 'X'))			{				c = s[1];				s+=2;				base = 16;			}			if (base == 0)			{				base = c=='0' ? 8:10;			}			cutoff = neg? LONG_MIN:LONG_MAX;			cutlim = cutoff %base;			cutoff /= base;			if (neg )			{				if (cutlim > 0)				{					cutlim -=  base;					cutoff += 1;				}				cutlim = -cutlim;			}			for (acc =0, any=0;;c=(unsigned char)*s++)			{				if (isdigit(c))					c -= '0';				else if (isalpha(c))					c -= isupper(c) ? 'A'-10 : 'a'-10;				else 					break;				if (c >= base)					break;				if(any < 0)					continue;				if (neg)				{					if (acc < cutoff || (acc==cutoff && c>cutlim))					{						any = -1;						acc = LONG_MIN;					} 					else					{						any = 1;						acc *= base;						acc -= c;					}				} 				else				{					if (acc>cutoff || (acc==cutoff && c>cutlim))					{						any = -1;						acc = LONG_MAX;					} 					else					{						any = 1;						acc *= base;						acc += c;					}				}			}			if(endptr != 0)				*endptr = (char *)(any? s-1:nptr);			return acc;		}    int atoi(const char *str) {        return strtol(str, NULL, 10);    }};

转载地址:http://ubxti.baihongyu.com/

你可能感兴趣的文章
SVG 基础学习之——SVG 参考手册
查看>>
mysql中用命令行复制表结构的方法
查看>>
hbase shell出现ERROR: org.apache.hadoop.hbase.ipc.ServerNotRunningYetException
查看>>
换位思考真的是一个很好的习惯
查看>>
Spring Cloud 架构,例子
查看>>
让代码变得更优雅-Lombok
查看>>
liquibase的使用
查看>>
代码生成器-mybatis-generator的使用
查看>>
Lambda表达式之List的常用方法
查看>>
lambda 表达式遍历map和list
查看>>
全局异常处理代码
查看>>
sql分组取组内的最新数据
查看>>
Java入门之编程基础(一)
查看>>
Java入门之编程基础(二)
查看>>
Java入门之编程基础(三)
查看>>
Java入门之编程基础(四)
查看>>
Java入门之编程基础(五)
查看>>
Java入门之面对对象
查看>>
Java入门之API的使用及String 和StringBuilder类的常见方法
查看>>
Java入门之对象数组及集合概述
查看>>