美文网首页
LeetCode算法题-Easy-Math(168、171)

LeetCode算法题-Easy-Math(168、171)

作者: Dane_404 | 来源:发表于2019-02-14 18:53 被阅读0次

技巧是:利用char 'Z'和'A'对应ASCII的值

168.Excel Sheet Column Title

题目: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
...
Example 1:
Input: 1
Output: "A"
Example 2:
Input: 28
Output: "AB"
Example 3:
Input: 701
Output: "ZY"

class Solution {
    public String convertToTitle(int n) {
        
        int letterLen = (int)'Z' - (int)'A'+1;
        int a = (int)'A';
       
        StringBuffer sb = new StringBuffer();
     
        while(n > 0 ){
          
            n--;
            char c =(char)(a + n%letterLen );
            sb.append(c);
            n /=letterLen;  
          
        }
        
       return sb.reverse().toString();
    }
}

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
...
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701

class Solution {
    public int titleToNumber(String s) {
        
        char[] c = s.toCharArray(); 
        int result = 0;
        for(int i = 0 ; i < c.length;i++){
            
           result = result*26 + c[i] - 'A'+1 ;
            
        }
        
        return result;
    }
}

相关文章

网友评论

      本文标题:LeetCode算法题-Easy-Math(168、171)

      本文链接:https://www.haomeiwen.com/subject/xcdyeqtx.html