lintcode,转换字符串到整数
来源:互联网 发布:搜索游戏的软件 编辑:程序博客网 时间:2024/05/22 12:26
实现atoi这个函数,将一个字符串转换为整数。如果没有合法的整数,返回0。如果整数超出了32位整数的范围,返回INT_MAX(2147483647)如果是正整数,或者INT_MIN(-2147483648)如果是负整数。
样例
“10” =>10
“-1” => -1
“123123123123123” => 2147483647
“1.0” => 1
解题思路:字符串处理,注意细节,包括去除空格,判断首位是哪种符号,代码写出来很烂,不过一刷ac了。
public class Solution { /** * @param str: A string * @return An integer */ public int atoi(String str) { if(str == null || str.length() == 0) return 0; str = str.trim(); char flag = str.charAt(0); double res = 0; if(flag == '+' || flag == '-'){ for(int i = 1; i < str.length(); i++){ if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){ int tmp = str.charAt(i) - '0'; res = res * 10 + tmp; if(res > Integer.MAX_VALUE){ return Integer.MIN_VALUE; } }else{ break; } } if(flag == '-') return (int)(-1*res); }else{ for(int i = 0; i < str.length(); i++){ if(str.charAt(i) >= '0' && str.charAt(i) <= '9'){ int tmp = str.charAt(i) - '0'; res = res * 10 + tmp; if(res > Integer.MAX_VALUE){ return Integer.MAX_VALUE; } }else{ break; } } } return (int)res; }}
看了下别人的思路,代码干净一些。
public class Solution { /** * @param str: A string * @return An integer */ public int atoi(String str) { if(str == null || str.length() == 0) return 0; str = str.trim(); char flag = '+'; int i = 0; if(str.charAt(0) == '+'){ i++; } if(str.charAt(0) == '-'){ i++; flag = '-'; } double res = 0; while(i < str.length() && str.charAt(i) <= '9' && str.charAt(i) >= '0'){ res = res * 10 + str.charAt(i) - '0'; i++; } if(flag == '-'){ res = -1 * res; } if(res > Integer.MAX_VALUE) return Integer.MAX_VALUE; if(res < Integer.MIN_VALUE) return Integer.MIN_VALUE; return (int)res; }}
0 0
- lintcode-转换字符串到整数
- lintcode,转换字符串到整数
- Lintcode 转换字符串到整数
- lintcode -- 转换字符串到整数
- LintCode:转换字符串到整数
- lintcode 转换字符串到整数
- 转换字符串到整数——LintCode
- lintcode之转换字符串到整数
- LintCode 54- 转换字符串到整数
- LintCode 54 转换字符串到整数
- [LintCode]54.转换字符串到整数
- LINTCODE——转换字符串到整数
- LintCode-剑指Offer-(54)转换字符串到整数
- 转换字符串到整数
- 转换字符串到整数
- 转换字符串到整数
- 转换字符串到整数
- Miscellaneous | 转换字符串到整数
- MyBatis 向Sql语句中动态传参数·动态SQL拼接
- 『sklearn学习』多种模型预测脸的下半部分的结果对比
- CocoaPods安装和使用教程
- AlertDialog对话框的使用
- Unity 动画回调
- lintcode,转换字符串到整数
- Torch7的使用之基本知识
- java web学习笔记-@Controller @RequestMapping注解
- Java做高精度计算(BigDecimal类)
- 润乾报表如何实现行式报表新添加行单元格始终可写
- Unity 从Animator组件中获得AnimationClip
- okhttp-上传文件
- windows下mongodb安装图文教程(整理)
- ubuntu win10 双系统 grub2 修复