当前位置: 代码迷 >> 综合 >> [LeetCode 168] Excel Sheet Column Title
  详细解决方案

[LeetCode 168] Excel Sheet Column Title

热度:1   发布时间:2024-01-04 07:38:27.0



Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

    1 -> A2 -> B3 -> C...26 -> Z27 -> AA28 -> AB 

solution

10进制转为26进制

1.

public String convertToTitle(int n) {Map<Integer, String> numToString = new HashMap<>();for(int i=0;i<26;i++){char w = (char) ('A' + i);numToString.put(i, String.valueOf(w));}if(n<=26) return numToString.get(n-1);StringBuilder sb = new StringBuilder();while(n>0){int index = (n-1)%26;sb.append(numToString.get(index));n = (n-1)/26;}return sb.reverse().toString();}


2.

public String convertToTitle1(int n) {String result = "";while(n>0){result = (char)((n-1)%26 +'A') + result;n = (n-1)/26;}return result;}


  相关解决方案