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

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

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.

 

The heart of this problem is dealing with overflow. A direct approach is to store the number as a string so we can evaluate at each step if the number had indeed overflowed. There are some other ways to detect overflow that requires knowledge about how a specific programming language or operating system works.

A desirable solution does not require any assumption on how the language works. In each step we are appending a digit to the number by doing a multiplication and addition. If the current number is greater than 214748364, we know it is going to overflow. On the other hand, if the current number is equal to 214748364, we know that it will overflow only when the current digit is greater than or equal to 8. Remember to also consider edge case for the smallest number, –2147483648 (–231). 

 

1     private static final int maxDiv10 = Integer.MAX_VALUE/10; 2     public int myAtoi(String str) { 3         String s = str.trim(); 4         int i = 0, sign = 1; 5         if(i < s.length() && s.charAt(0) == '+') { 6             sign = 1; 7             i++; 8         } else if(i < s.length() && s.charAt(0) == '-'){ 9             sign = -1;10             i++;11         }12         int num = 0;13         while(i < s.length() && Character.isDigit(s.charAt(i))){14             int digit = Character.getNumericValue(s.charAt(i));15             if(num > maxDiv10 || num == maxDiv10 && digit >7){16                 return sign == 1 ? Integer.MAX_VALUE:Integer.MIN_VALUE;17             }18             num = num * 10 + digit;19             i++;20         }21         return num * sign;22     }

 

转载于:https://www.cnblogs.com/caomeibaobaoguai/p/4895016.html

你可能感兴趣的文章
C学习-第一个C语言(一)
查看>>
es6 generator函数
查看>>
matplotlib绘图(2)
查看>>
前端周刊第51期:1000个包的男人 + Vue.js + React Native + 奇技淫巧
查看>>
Docker入门(五)- link连接容器
查看>>
百度地图开发坐标问题总结
查看>>
数组基础知识
查看>>
复杂业务下,我们为何选择Akka作为异步通信框架?
查看>>
NPM发布新的安全功能
查看>>
Google Chrome开发者工具更新
查看>>
华为起诉美国政府,曝其服务器曾被美国政府入侵
查看>>
重磅!阿里巴巴Blink正式开源,重要优化点解读\n
查看>>
RPC框架的可靠性设计
查看>>
仅售99美元!英伟达发布最小AI计算机Jetson Nano
查看>>
如何在复杂的分布式系统中做测试
查看>>
Faiss:Facebook开源的相似性搜索类库
查看>>
Nexus指南已经发布
查看>>
小米:开源不仅要站在巨人的肩膀上,还要为巨人指方向
查看>>
GitHub 重磅更新:无限私有仓库免费使用
查看>>
推荐10个CI/CD工具,用于云平台集成交付
查看>>