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. C# Object reference not set to an instance of an object.

    一.问题 Object reference not set to an instance of an object. (你调用的对象是空的) 二.解决问题 在使用 c# 的查询时,先筛选后在关联其他表 ...

  2. Centos7 安装MySQL 5.7 (通用二进制包)

    1.下载安装包 下载地址 https://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.17-linux-glibc2.5-x86_64.tar.gz ...

  3. HDP3.1 中 YRAN 和 MR2 的内存大小配置的计算方式

    Container 是 YARN 中基本的处理单元,它是对内存.CPU等计算的封装.总的来说,每个core每块硬盘 分配2个 container,能获得较好的集群利用率. 1. 确定可用内存大小. 对 ...

  4. 白白的(baibaide)——树状数组套主席树+splay

    题目 [题目描述] 有一个长度为 $n$ 的序列 $a_1, a_2, \dots, a_n$,一开始每个位置都是白色.如果一个区间中每个位置都是白色,则称这是一个白白的区间.如果一个白白的区间向左或 ...

  5. Java 引用类型

    若内存中一个对象没有任何引用的话,则可以认为该对象已经不再使用了,可以成为GC的候选.不过由于垃圾回收器的运行时间不确定,可被垃圾回收的对象的实际被回收时间是不确定的.对于一个对象来说,只要有引用的存 ...

  6. POJ2151-Check the difficulty of problems

    题目链接:点击打开链接 Check the difficulty of problems Time Limit: 2000MS   Memory Limit: 65536K Total Submiss ...

  7. k8s yaml文件详解

    1.yaml格式的Pod配置文件内容及注解 深入Pod之前,首先我们来了解下Pod的yaml整体文件内容及功能注解. 如下: # yaml格式的pod定义文件完整内容: apiVersion: v1 ...

  8. atom快捷键

    文件切换 ctrl-shift-s 保存所有打开的文件 cmd-shift-o 打开目录 cmd-\ 显示或隐藏目录树 ctrl-0 焦点移到目录树 目录树下,使用a,m,delete来增加,修改和删 ...

  9. 默认约束 default

    default :初始值设置,插入记录时,如果没有明确为字段赋值,则自动赋予默认值.  例子:create table tb6(   id int primary key auto_increment ...

  10. Maven_setting.xml

    <?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Soft ...