`
daojin
  • 浏览: 677263 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

Android面试题目之三: 字符串转整形

 
阅读更多

1. 首先写了一个字符串转整形的算法:

	public static class String2Int1 implements String2Int {
		@Override
		public int string2int(String str) {
			int value = 0;
			int pow10 = 1;
			for (int j = str.length() - 1; j >= 0; --j) {
				char charValue = str.charAt(j);
				if (charValue == '-' && j == 0) {
					value = -value;
					break;
				}
				if (charValue == '+' && j == 0) {
					break;
				}
				value = value + (charValue - '0') * pow10;
				pow10 = pow10 * 10;
			}
			return value;
		}
	}
	

 打印时间:

  

1the time is 3143, strValue = -1001213121

 

2. 测试了Android SDK的算法:

	public static class String2Int2 implements String2Int {
		@Override
		public int string2int(String str) {
		return Integer.valueOf(str);
		}
	}

 打印时间:

 

1the time is 7980, strValue = -1001213121

 

   Android SDK 算法比自己实现的算法慢了一倍。但是,自己实现的算法可不可以改进呢。

3. 改进的算法:从左向右怎么样呢,是不是可以快速一点:

	public static class String2Int2 implements String2Int {
		@Override
		public int string2int(String str) {
			int result = 0;
			boolean negative = false;
			int i = 0, len = str.length();
			int digit;
			char firstChar = str.charAt(0);
			if (firstChar < '0') { // Possible leading "+" or "-"
				if (firstChar == '-') {
					negative = true;
				}
				i++;
			}
			while (i < len) {
				digit = str.charAt(i++) - '0';
				result *= 10;
				result += digit;
			}
			return negative ? -result : result;
		}
	}

 打印时间:

 

1the time is 2774, strValue = -1001213121

 

 

总结

由此可见。最后一个算法减少了乘法运算的次数,因此速度要快一点。


如果您看了有收获,那么下载一个APl软件支持一下博主吧!还可以解决您的密码太多记不住的烦恼哦。

源码下载链接:

http://a.app.qq.com/o/simple.jsp?pkgname=com.wa505.kf.epassword

 

 

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics