String to Integer (atoi)
2016-05-08 19:16
525 查看
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.
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.
public class Solution { public int MyAtoi(string str) { int i = 0; while (i < str.Length && str[i] == ' ') ++i; if (i == str.Length) return 0; int sign = 1; if (str[i] == '+') ++i; else if (str[i] == '-') { ++i; sign = -1; } if (i == str.Length) return 0; long ret = 0; while (i < str.Length && char.IsDigit(str[i])) { ret = ret * 10 + (str[i] - '0'); if (sign > 0 && ret >= int.MaxValue) return int.MaxValue; if (sign < 0 && ret > int.MaxValue) return int.MinValue; ++i; } return (int)(sign * ret); } }
相关文章推荐
- atoi实现,考虑溢出等各种情况
- atio函数的重写
- 关于字符串操作
- 959a C程序设计语言第33页2.7节提到的atoi程序
- LeetCode_String to Integer (atoi)
- atoi()函数实现
- atoi 的 C 语言实现
- String to Integer (atoi)
- LeetCode - String to Integer (atoi) 题解
- unix下c编程成长之路-------字符串与整型之间的转换
- ATOI函数-代码实例
- String to Integer (atoi)
- Qt(C++)将字符串输入框中的数字字符串转换成十六进制命令的方法。
- C语言字符串
- atoi itoa 等格式转化
- ip地址转换为unsigned int,unsigned int 转换成ip地址
- leetcode笔记:String to Integer (atoi)
- leetcode笔记:Evaluate Reverse Polish Notation(逆波兰式的计算)
- 《剑指offer》把字符串转换成整数
- C\C++字符串转化成整数