现给你一个仅由大写字母组成的字符串,表示Excel表格里面的列名称。比如字符串A的序号为1,字符串B的序号为2,字符串Z的序号为26,字符串 AA的序号为27,请输出该字符串的序号。
且在字符串到范围内
#include <cctype> class Solution { public: int getNumber(string S) { // write code here string new_str = ""; for (int i = 0; i < S.length(); i++) { new_str += toupper(S[i]); } int res = 0; for (int i = new_str.length() - 1; i >= 0; i--) { int weight = new_str.length() - 1 - i; res += (new_str[i] - 'A' + 1) * pow(26, weight); } return res; } };
public class GetNumber { public int getNumber(String S) { // write code here S = S.toUpperCase(Locale.ROOT); char[] chars = S.toCharArray(); int number = 0; for (int i = 0; i < chars.length; i++) { int num = chars[i] - 'A' + 1; number = number * 26 + num; } return number; } }
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param S string字符串 * @return int整型 */ public int getNumber(String S) { // write code here int result = 0; if (S == null || "".equals(S)) { return 0; } char[] chars = S.toCharArray(); for (int i = chars.length - 1; i >= 0; i--) { int v = (int) ((chars[i] - 'A' + 1) * Math.pow(26, chars.length - 1 - i)); result += v; } return result; } }
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param S string字符串 # @return int整型 # class Solution: def getNumber(self , S: str) -> int: # write code here d = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' n = 0 i = 0 S = S[::-1] for c in S: cn = d.index(c) + 1 for j in range(i): cn = cn * 26 n += cn i += 1 return n