Android Interview Question No. 3: String Transformation

1. First write an algorithm for converting a string to a shape:

	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;
		}
	}
	

 Print Time:

  

1the time is 3143, strValue = -1001213121

 

2. Tested the algorithm of Android SDK:

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

 Print Time:

 

1the time is 7980, strValue = -1001213121

 

   The Android SDK algorithm is twice as slow as the self-implemented algorithm. However, can the algorithm implemented by yourself be improved?

3. Improved algorithm: how about from left to right, can it be faster:

	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;
		}
	}

 Print Time:

 

1the time is 2774, strValue = -1001213121

 

 

Summarize

It can be seen from this. The last algorithm reduces the number of multiplications and is therefore a bit faster.


If you see something, then download an APl software to support bloggers! It can also solve the trouble that you have too many passwords to remember.

Source code download link:

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

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326245117&siteId=291194637