剑指offer 49. 把字符串转换成整数
来源:互联网 发布:淘宝运动鞋女质量 编辑:程序博客网 时间:2024/05/22 15:34
// 字符串转换为整数 : atoi//// 可能的输入:// 1 带符号数// 2 无符号数// 3 零// 4 空指针// 5 超出表示范围 – 暂时仅仅是直接退出且设置最小 – 可以考虑此时抛个异常// 6 非法输入,比如并不是一个0-9或者+ -组成的字符串 – 对于非法输入一律返回的是Integer.MIN_VALUEpublic class Main {public static void main(String[] args) throws Exception {String str1 = "123456";String str2 = "-123456";String str3 = "-6";String str4 = "-";String str5 = "+1";String str6 = "+abc";String str7 = null;System.out.println(strToInt(str1));System.out.println(strToInt(str2));System.out.println(strToInt(str3));System.out.println(strToInt(str4));System.out.println(strToInt(str5));System.out.println(strToInt(str6));System.out.println(strToInt(str7));}public static int strToInt(String str) throws Exception {if(str == null){return Integer.MIN_VALUE;}for(int i = 0;i<str.length();i++){if(!judge(str.charAt(i))){return Integer.MIN_VALUE;}}double value = 0;if(str.charAt(0) == '+' || str.charAt(0) == '-'){value = trans(str.substring(1));if(str.charAt(0) == '-'){return (int)value*-1;}else{return (int)value;}}else{value = trans(str);return (int)value;}}public static boolean judge(char c){if(c == '+' || c == '-'){return true;}if(c<='9' && c>='0'){return true;}return false;}public static double trans(String str){double result = 0;for(int i = 0;i<str.length();i++){result = result+(str.charAt(i)-'0')*Math.pow(10,str.length()-i-1);}return result;}}
0 0
- 剑指offer--把字符串转换成整数
- 《剑指offer》把字符串转换成整数
- 《剑指offer》把字符串转换成整数
- [剑指offer]把字符串转换成整数
- 剑指offer|把字符串转换成整数
- 《剑指offer》-把字符串转换成整数
- 剑指offer 把字符串转换成整数
- 剑指offer: 把字符串转换成整数
- 【剑指offer】把字符串转换成整数
- 剑指offer--把字符串转换成整数
- 把字符串转换成整数 剑指offer
- 剑指offer:把字符串转换成整数
- 剑指offer 49. 把字符串转换成整数
- 剑指offer-49.把字符串转换成整数
- 剑指offer-把字符串转换为整数
- 【剑指offer】题目1508:把字符串转换成整数
- 剑指offer--面试题49:把字符串转换成整数
- 剑指offer——把字符串转换成整数
- mybatis使用spring-druid数据源连接池配置log4j打印sql语句以及开启监控平台
- C++知识点
- bzoj1494: [NOI2007]生成树计数
- Linux下MySQL数据库基本操作
- 博客停止更新,转移至 http://www.bendawang.site/
- 剑指offer 49. 把字符串转换成整数
- Python基础一
- 数据库垂直拆分
- Servlet中不可不知的Session技术
- 彻底弄懂Java中的equals()方法以及与"=="的区别
- ps和grep 的用法
- 应用内存优化之OnLowMemory&OnTrimMemory
- [HDU 2167]Pebbles:状压DP
- android 根据子view动态设置listview的高 有转载内容,已标明原地址