【剑指offer-Java版】49把字符串转换为整数
2016-04-27 09:48
489 查看
字符串转换为整数 : atoi
可能的输入:
1 带符号数
2 无符号数
3 零
4 空指针
5 超出表示范围 – 暂时仅仅是直接退出且设置最小 – 可以考虑此时抛个异常
6 非法输入,比如并不是一个0-9或者+ -组成的字符串 – 对于非法输入一律返回的是Integer.MIN_VALUE
测试代码:
可能的输入:
1 带符号数
2 无符号数
3 零
4 空指针
5 超出表示范围 – 暂时仅仅是直接退出且设置最小 – 可以考虑此时抛个异常
6 非法输入,比如并不是一个0-9或者+ -组成的字符串 – 对于非法输入一律返回的是Integer.MIN_VALUE
public class _Q49<T> { public long StrToInt(String str){ if(str == null) return Long.MIN_VALUE; // 输入非法还是抛异常提示或者约定 if(str.length() == 0) return 0; // 判断输入字符串是否合法 for (int i = 0; i < str.length(); i++) { if (!judge(str.charAt(i))) { return Long.MIN_VALUE; } } char chars[] = str.toCharArray(); long result = 0; if(chars[0] == '-' || chars[0] == '+'){ // 有符号数 result = trans(str.substring(1)); }else{ // 无符号数 result = trans(str); } if(result > 0 && chars[0] == '-') result = -result; return result; } private long trans(String str){ if(str.length() == 0) return 0; long result = 0; for(int i=0; i<str.length(); i++){ result = result*10 + (str.charAt(i)-'0'); if(result > Long.MAX_VALUE){ result = Long.MIN_VALUE; break; } } return result; } private boolean judge(char c){ if(c == '-' || c == '+') return true; if(c >= '0' && c <= '9') return true; return false; } }
测试代码:
public class _Q49Test extends TestCase { _Q49<?> a2i = new _Q49(); public void test(){ String str1 = "123456"; String str2 = "-123456"; String str3 = "-6"; String str4 = "-"; String str5 = "+1"; String str6 = "+abc"; String str7 = null; System.out.println(a2i.StrToInt(str1)); System.out.println(a2i.StrToInt(str2)); System.out.println(a2i.StrToInt(str3)); System.out.println(a2i.StrToInt(str4)); System.out.println(a2i.StrToInt(str5)); System.out.println(a2i.StrToInt(str6)); System.out.println(a2i.StrToInt(str7)); } }
相关文章推荐
- javascript实现延时显示提示框特效代码
- 【剑指offer-Java版】47不用加减乘除做加法
- [转载]最全前端资源汇集
- JS延时器提示框的应用实例代码解析
- 【剑指offer-Java版】46求 1 + 2 + 3 + ... + n
- 【剑指offer-Java版】45圆圈中最后剩下的数字
- [乐意黎原创] Local 为德文时,小数点(点号)变成逗号时的JS 前端处理方法
- 【剑指offer-Java版】44扑克牌的顺子
- 【剑指offer-Java版】43n个骰子的点数
- 【剑指offer-Java版】42翻转单词顺序VS左旋转字符串
- c# JSON序列化与反序列化
- 【剑指offer-Java版】41和为s的两个数字VS和为s的连续正数序列
- 【剑指offer-Java版】40数组中只出现一次的数字
- js 函数前的+号
- 【剑指offer-Java版】39二叉树的深度
- caffe 如何训练自己的数据图片
- 获取MainFest中MetaData对应的key节点数据
- web与js的简单交互
- div、css圆形头像
- JavaScript 高级技巧