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.

将一个字符串转化为 int 型。

1. null or empty string
2. white spaces
3. +/- sign
4. calculate real value
5. handle min & max
public int atoi(String str) {
if (str == null || str.length() < 1)
return 0; // trim white spaces
str = str.trim(); char flag = '+'; // check negative or positive
int i = 0;
if (str.charAt(0) == '-') {
flag = '-';
i++;
} else if (str.charAt(0) == '+') {
i++;
}
// use double to store result
double result = 0; // calculate value
while (str.length() > i && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
result = result * 10 + (str.charAt(i) - '0');
i++;
} if (flag == '-')
result = -result; // handle max and min
if (result > Integer.MAX_VALUE)
return Integer.MAX_VALUE; if (result < Integer.MIN_VALUE)
return Integer.MIN_VALUE; return (int) result;
}
class Solution:
# @return an integer
def atoi(self, str):
str = str.strip()
if not str:
return 0 MAX_INT = 2147483647
MIN_INT = -2147483648
ret = 0
overflow = False
pos = 0
sign = 1 if str[pos] == '-':
pos += 1
sign = -1
elif str[pos] == '+':
pos += 1 for i in range(pos, len(str)):
if not str[i].isdigit():
break
ret = ret * 10 + int(str[i])
if not MIN_INT <= sign * ret <= MAX_INT:
overflow = True
break if overflow:
return MAX_INT if sign == 1 else MIN_INT
else:
return sign * ret
# 正则表达式
class Solution:
# @return an integer
def atoi(self, str):
str = str.strip()
str = re.match(r'^[+-]?\d+', str).group()
MAX_INT = 2147483647
MIN_INT = -2147483648 try:
ret = int(str)
if ret > MAX_INT:
return MAX_INT
elif ret < MIN_INT:
return MIN_INT
else:
return ret
except:
return 0

8. String to Integer的更多相关文章

  1. 【leetcode】String to Integer (atoi)

    String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully consider ...

  2. No.008 String to Integer (atoi)

    8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...

  3. 【LeetCode】7 & 8 - Reverse Integer & String to Integer (atoi)

    7 - Reverse digits of an integer. Example1: x = 123, return 321Example2: x = -123, return -321 Notic ...

  4. leetcode第八题 String to Integer (atoi) (java)

    String to Integer (atoi) time=272ms   accepted 需考虑各种可能出现的情况 public class Solution { public int atoi( ...

  5. leetcode day6 -- String to Integer (atoi) &amp;&amp; Best Time to Buy and Sell Stock I II III

    1.  String to Integer (atoi) Implement atoi to convert a string to an integer. Hint: Carefully con ...

  6. String to Integer (atoi) - 字符串转为整形,atoi 函数(Java )

    String to Integer (atoi) Implement atoi to convert a string to an integer. [函数说明]atoi() 函数会扫描 str 字符 ...

  7. Kotlin实现LeetCode算法题之String to Integer (atoi)

    题目String to Integer (atoi)(难度Medium) 大意是找出给定字串开头部分的整型数值,忽略开头的空格,注意符号,对超出Integer的数做取边界值处理. 方案1 class ...

  8. String与Integer问题

    今天分享一下关于最近面试的问题,临近春节,而我在茫茫人海中奔波,今天面试了来到了中关村科技园,挺气派的,之前也是在外面看看,今天就去了,心里有点激动,恰好,正好赶上了上班时,看见它们的努力,我感到再累 ...

  9. LeetCode--No.008 String to Integer (atoi)

    8. String to Integer (atoi) Total Accepted: 112863 Total Submissions: 825433 Difficulty: Easy Implem ...

  10. leetcode-algorithms-8 String to Integer (atoi)

    leetcode-algorithms-8 String to Integer (atoi) Implement atoi which converts a string to an integer. ...

随机推荐

  1. 简单的html兼容(参考js和css的常规写法)

    参考往常css/js的浏览器选择加载 <!--[if lte IE 8]> <link rel="stylesheet" href="IEBrower. ...

  2. SpringBoot第五篇:整合Mybatis

    作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10869315.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言   ORM框架 ...

  3. Java8 使用 stream().sorted()对List集合进行排序

    集合对像定义 集合对象以学生类(StudentInfo)为例,有学生的基本信息,包括:姓名,性别,年龄,身高,生日几项. 使用stream().sorted()进行排序,需要该类实现 Comparab ...

  4. 位运算 之(1) 按位与(AND)& 操作

    文章作者:ktyanny 由于位运算直接对内存数据进行操作,不需要转成十进制,因此处理速度非常快. 按位与(Bitwise AND),运算符号为& a&b 的操作的结果:a.b中对应位 ...

  5. 洛谷P4878 [USACO05DEC]layout布局

    题目描述 正如其他物种一样,奶牛们也喜欢在排队打饭时与它们的朋友挨在一起.\(FJ\) 有编号为 \(1\dots N\) 的 \(N\) 头奶牛 \((2\le N\le 1000)\).开始时,奶 ...

  6. 关于node中的global,箭头函数的this的一个小问题

    this一直是一个JS中的困扰问题,这次在跑JS精粹的代码的时候顺带发现了Node里面全局变量的问题 var x = 1; var myObj = { x: 2 }; myObj.func = fun ...

  7. FTP原理与配置

    FTP(file transfer protocol)文件传输协议(基于tcp协议).是用来传送文件的协议,使用FTP实现文件传输的同时,还可以保证数据传输的可靠性和高效性.通过学习我们需要掌握以下两 ...

  8. 积分图像的应用(二):非局部均值去噪(NL-means)

    非局部均值去噪(NL-means)一文介绍了NL-means基本算法,同时指出了该算法效率低的问题,本文将使用积分图像技术对该算法进行加速. 假设图像共像个素点,搜索窗口大小,领域窗口大小, 计算两个 ...

  9. mysql主从复制之同步部分库表

    这里以mariadb为例,和mysql一样的配置 系统:centos7 主服务器:192.168.0.1:3305(两台服务器都做过时间同步) 从服务器:192.168.0.2:3306(两台服务器都 ...

  10. 页面上AJAX调用数据

    <div class="section page9" data-page='9'> <div class="global-section-wrp med ...