题目
Related to question: Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
我的解法
很明显,26进制转换为十进制
我的代码:
public class Solution {
public int titleToNumber(String s) {
int result = 0;
for (int i = 0; i < s.length(); ++i) {
char ch = s.charAt(i);
result = (ch - 64) + 26 * result;
}
return result;
}
}
主要注意的是java中String类的方法使用。这里用到了length()和charAt(i)方法,分别是获取字符串长度和位于i位置的字符(i从0开始)。
其他String类的方法:
构造函数:
String(byte[ ] bytes):通过byte数组构造字符串对象。
String(char[ ] value):通过char数组构造字符串对象。
String(Sting original):构造一个original的副本。即:拷贝一个original。
String(StringBuffer buffer):通过StringBuffer数组构造字符串对象。
其他常用方法:
public char charAt(int index)
返回字符串中第index个字符;
public int length()
返回字符串的长度;
public int indexOf(String str)
返回字符串中第一次出现str的位置;
public int indexOf(String str,int fromIndex)
返回字符串从fromIndex开始第一次出现str的位置;
public boolean equalsIgnoreCase(String another)
比较字符串与another是否一样(忽略大小写);
public String replace(char oldchar,char newChar)
在字符串中用newChar字符替换oldChar字符
public boolean startsWith(String prefix)
判断字符串是否以prefix字符串开头;
public boolean endsWith(String suffix)
判断一个字符串是否以suffix字符串结尾;
public String toUpperCase()
返回一个字符串为该字符串的大写形式;
public String toLowerCase()
返回一个字符串为该字符串的小写形式
public String substring(int beginIndex)
返回该字符串从beginIndex开始到结尾的子字符串;
public String substring(int beginIndex,int endIndex)
返回该字符串从beginIndex开始到endsIndex结尾的子字符串
public String trim()
返回该字符串去掉开头和结尾空格后的字符串
public String[] split(String regex)
将一个字符串按照指定的分隔符分隔,返回分隔后的字符串数组