原题链接在这里: https://leetcode.com/problems/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
题解:
不是从0开始算,这里是从1算起. 算之前先对n进行n-1处理再取余数。
Time Complexity: O(res.length()).
Space: O(res.length()).
AC Java:
1 class Solution { 2 public String convertToTitle(int n) { 3 if(n <= 0){ 4 throw new IllegalArgumentException("Invalid input integer."); 5 } 6 7 StringBuilder sb = new StringBuilder(); 8 while(n != 0){ 9 sb.insert(0, (char)('A'+(n-1)%26)); 10 n = (n-1)/26; 11 } 12 13 return sb.toString(); 14 } 15 }
recursion写法.
Time Complexity: O(res.length()). Space: O(res.length()).
AC Java:
1 class Solution { 2 public String convertToTitle(int n) { 3 if(n == 0){ 4 return ""; 5 } 6 7 n = n-1; 8 return convertToTitle(n/26) + (char)('A'+ (n%26)); 9 } 10 }