(letcode)String to Integer (atoi)
2024-10-18 02:27:04
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.
问题:将字符窜转换成数字
分析:感觉题目不难,但是细节很多,容易想不到
1.数字前面有空格 如s=“ 123456”
2.数字前出现了不必要或多于1个的字符导致数字认证错误,输出0 如s=“ b1234” ,s=“ ++1233” , s=“ +-1121”
3.数字中出现了不必要的字符,返回字符前的数字 如s=“ 12a12” , s=“ 123 123”
4.数字越界 超过了范围(-2147483648--2147483647) 若超过了负数的 输出-2147483648 超过了正数的输出2147483647
在科普一个知识点,倘若某个数超过了2147483647则会变为负数,反过来一样
class Solution {
public:
int myAtoi(string str) {
long long result = ;
int i = ;
int flag1 = ;
int flag2 = ;
if(str.empty()) return ;
while(str[i] != '\0' && str[i] == ' ') i++;
while(str[i] == '-') { flag1++;i++; }
while(str[i] == '+') { flag2++;i++; }
while(i < str.length())
{
if(str[i] >= '' && str[i] <= '')
{
if(flag1 > ||flag2> || (flag1 == &&flag2 == ))
{
result = ;
break;
}
else if(flag1 == )
{
result = result * - (str[i]-'');
if(result < INT_MIN) result = INT_MIN;
}
else
{
result = result * + (str[i]-'');
if(result > INT_MAX) result = INT_MAX;
}
i++;
}
else
{
break;
}
}
int num = (int)result;
return num;
}
};
最新文章
- 无法启动程序 ”*.lib”
- The 2015 China Collegiate Programming Contest G. Ancient Go hdu 5546
- 安装和使用sass
- HTML5 中canvas支持触摸屏的签名面板
- HTTP MIME类型即HttpResponse.ContentType属性值列表
- vi编辑器基本用法介绍
- Python学习 之 文件
- css3学习笔记之多列
- 前端--关于客户端javascript
- Spring MVC 处理异常的3种方式
- C语言与java语言中数据类型的差别总结
- Python题集:2019春Python程序设计选修课习题笔记
- [LeetCode] Random Pick with Blacklist 带黑名单的随机选取
- [PHP] PHP闭包(closures)
- RMAN restore fails with ORA-01180: can not create datafile 1
- hadoop 伪分布式搭建
- GIT好文搜藏
- 052 kafka对topic的增删改查操作
- springboot2.0动态多数据源切换
- P1006 传纸条-洛谷luogu-dp动态规划