Topic description : In Microsoft Excel, use A for column 1, B for column 2... Z for column 26, AA for column 27, AB for column 28... and so on. Please write a function, enter the column number in letters, enter the column number it is.
For example: Input: HAT - Output: 5454, Input: AA - Output: 27,
Analysis of the topic : From the requirements of the topic, we need to implement a function that converts the input string into an integer, and this requirement actually requires us to represent the input in hexadecimal (twenty-six represented by A~Z). hexadecimal) strings are converted to decimal.
Analysis of ideas : For example, if we want to convert the hexadecimal ABC into decimal, we do this: A * 26^2 + B * 26^1 + C * 26^0, then we can use this general formula Deduce its general expression: weight(A) * 26^n, weight(A) represents the value represented in hexadecimal, n represents the position of A in the string, n = length - i - 1, i represents the position of the character ch in the string.
Code implementation :
package IQ15;//Interview questions /** * * @author Kang Xi * Question: In Excel, use A for column 1, B for column 2..., Z for column 26, AA for column 27, AB for column 28..., and so on . Please write a function, * Enter the column number code represented by letters, and output which column he is. * */ public class Test { /** * Convert decimal to hexadecimal (hexadecimal represented by A~Z) * Here we use the reverse remainder method to convert decimal to hexadecimal * @param n * @return */ private static StringBuffer DecimalToTwentysix(int n) { StringBuffer result = new StringBuffer(); while(n > 0) { int remainder = n % 26; result.append((char)(remainder + 64));//The ASCII code value of uppercase A is 65 n = n/26; } return result.reverse();//String reverse } /** * Convert hexadecimal to decimal * @param str * @return */ private static int TwentysixToDecimal(String str) { String strWeight = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; int result = 0; for(int i = 0; i < str.length(); i++) { char ch = str.charAt(i); int weight = weight(strWeight, ch); result += Math.pow(26, str.length()-i-1) * weight; } return result; } //Return the weight represented by the character ch in str private static int weight(String str, char ch) { int weight = 0; for(int i = 0; i < str.length(); i++) { if(str.charAt(i) == ch) { weight = i+1; } } return weight; } public static void main(String[] args) { System.out.println(TwentysixToDecimal("HAT")); System.out.println(DecimalToTwentysix(5454)); } }