Excel Sheet Column Title

mac2022-06-30  72

 

 

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

The key is n--. The minimum in 26-bit number is mapped to 1, not 0.

 

public class Solution { public String convertToTitle(int n) { if(n<=0)return ""; StringBuilder sb = new StringBuilder(); while(n>0) { n--; char c = (char)(n&+'A'); sb.append(c); n = n/26; } sb.reverse(); return sb.toString(); } }

reference: http://www.programcreek.com/2014/03/leetcode-excel-sheet-column-title-java/

 

 

另一种解法:

public class Solution { public String convertToTitle(int n) { StringBuilder result = new StringBuilder(); while(n>0){ n--; result.insert(0, (char)('A' + n % 26)); n /= 26; } return result.toString(); } }

reference: https://leetcode.com/discuss/19150/accepted-java-solution

转载于:https://www.cnblogs.com/hygeia/p/5472503.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)