【171】Excel Sheet Column Number
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进制的数字转换表,用一个数在for循环内纪录字符的位数,从而乘以基数26
public class Solution { public int titleToNumber(String s) { if(s==null||s.length()==0){ return 0; } int base = 0; for(int i = 0; i<s.length();i++){ base = base*26 + s.charAt(i)-'A'+1;//当有两位数的时候,base就是个位数*26 } return base; } }
逆问题:Excel Sheet Column Title【168】
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB
思路:给n,用while循环,取出n的每一位,然后对应变换
首先看取出一个数的各个位用Java来实现:
while(n!=0){ System.out.println("result is "+ n%10); n = n/10; }//输入1234,则输出4,3,2,1
所以这个也是,依次取出各个位,然后跟A比较后转换
public class Solution { public String convertToTitle(int n) { StringBuilder result = new StringBuilder(); while(n!=0){ result.insert(0, (char)('A' + (n-1) % 26));//因为是26进制,但是是从1开始计数,所以要减一 n = (n-1)/ 26; } return result.toString(); } }