String to Integer
来源:互联网 发布:ultrawebgrid绑定数据 编辑:程序博客网 时间:2024/06/04 04:38
Q: Implement atoi to convert a string to an integer.
昨天很巧地在《剑指offer》的开篇看到了这个例子,作者举这个例子是为了强调程序的鲁棒性,鼓励我们在写代码之前就想好测试用例,避免程序漏洞导致系统运行崩溃,其实这在前面也提到过,还是那句话,想好所有可能会出现的情况再开始敲。
<span style="color:#333333;">public class Solution { public int atoi(String str) { int num = 0; int i = 0; if (str.length() == 0){ </span><span style="color:#ff0000;">//空字符串</span><span style="color:#333333;"> return 0; } char ch[] = str.toCharArray(); while (i < ch.length && ch[i] == ' '){ </span><span style="color:#ff0000;">//str = " 112233"</span><span style="color:#333333;"> i ++; } int t = i; int count = 0; while (ch[i] == '+' || ch[i] == '-'){ </span><span style="color:#ff0000;">//str = "+-2"</span><span style="color:#333333;"> i ++; count ++; } if (count > 1){ return 0; } int j = i; while (j < ch.length && Character.isDigit(ch[j])){ </span><span style="color:#ff0000;">//str = " 1122a33"</span><span style="color:#333333;"> j ++; } while (i < j) { if (ch[t] == '-'){ num += (-1) * (ch[i] - 48) * Math.pow(10, j - 1 - i); } else{ num += (ch[i] - 48) * Math.pow(10, j - 1 - i); } i ++; } return num; }}</span>
0 0
- string to integer & integer to string
- string to integer
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- [LeetCode]String to Integer
- string to integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer (atoi)
- String to Integer(atoi)
- String to Integer (atoi)
- A program to compute word length of a machine
- iOS中动画实现技术主要是:Core Animation。
- [csu oj]1553: Good subsequence(水题)
- Coursera上Andrew Ng机器学习课程总结(一)
- Balanced Binary Tree 平衡二叉树的判断
- String to Integer
- [图像]摄像机标定(2) 张正友标定推导详解
- Thinkphp学习笔记
- Minimum Depth of Binary Tree 二叉树的最小深度
- JQuery学习笔记之一
- HDU 5196 DZY Loves Inversions(离线+线段树)
- Python列表 元组 和字典
- jQuery中的.bind()、.live()和.delegate()之间区别分析
- 【爱上Linux】第一课 Linux概述