把字符串转换为整数
来源:互联网 发布:上海勇进软件 培训 编辑:程序博客网 时间:2024/05/21 19:15
题目描述
将一个字符串转换成一个整数,要求不能使用字符串转换整数的库函数。 数值为0或者字符串不是一个合法的数值则返回0
输入描述:
输入一个字符串,包括数字字母符号,可以为空
输出描述:
如果是合法的数值表达则返回该数字,否则返回0
输入例子:
+2147483647
1a33
输出例子:
2147483647
0
算法解析:
对于正确的数字形式为,123, +123, -123,对于这种形式的数字字符串,我们需要注意的是排除一些错误的形式,比如21+, +, 23e4,然后从后往前计算就好。
代码如下:
static int mState = 0; public static final int NORMAL = 0; public static final int EMPTY_POINT = 1; public static final int EMPTY_STRING = 2; public static final int ERROR = 3; public static int StrToInt(String str) { if (str == null) { mState = EMPTY_POINT; return 0; } else if (str.length() <= 0) { mState = EMPTY_STRING; return 0; } else if ((str.length() == 1) && (str.charAt(0) == '+' || str.charAt(0) == '-')) { mState = ERROR; return 0; } int result = 0; int temp = 1; for (int i = str.length() - 1; i >= 0; i--) { char c = str.charAt(i); if (c >= '0' && c <= '9') { result += (c - '0') * temp; temp *= 10; } else if (c == '+' && i == 0) { return result; } else if (c == '-' && i == 0) { return -result; } else { mState = ERROR; return 0; } } return result; }
0 0
- 把字符串转换为整数
- 把字符串转换为整数
- 把字符串转换为整数
- 把字符串转换为整数
- 把字符串转换为整数
- 把字符串转换为整数
- 把字符串转换为整数
- 把字符串转换为整数
- 把字符串转换为整数
- 把字符串转换为整数atoi
- c 把一整数转换为字符串
- 把一整数转换为字符串
- 把 字符串转换为整数的算法
- 把字符串转换为对应的整数
- 剑指offer-把字符串转换为整数
- 面试题33:把字符串转换为整数
- 编程算法 - 把字符串转换为整数 代码(C)
- 面试算法(四十九)把字符串转换为整数
- BZOJ 3325 偷龙
- JS框架,你会喜欢AngularJS
- 3、C语言流程控制 if...else、switch、for、while、do while
- CI3框架初识-自动加载之自定义config文件
- 动态规划之背包问题01
- 把字符串转换为整数
- gdb 中layout的使用
- OPENJUDGE 1.7 30:字符环
- maven学习笔记
- 互联网金融
- Glusterfs下读写请求的处理流程
- 累积缓冲区
- 公平锁与非公平锁
- GDAL写入FileGDB中文属性乱码问题