Excel Sheet Column Title

来源:互联网 发布:什么是ai设计软件 编辑:程序博客网 时间:2024/06/09 16:37



public class Solution {      public static String reverse(String string){          String newString = "";          for(int i = string.length() - 1; i>= 0; i--){              newString += string.charAt(i);          }          return newString;      }      public static String convertToTitle(int n) {          String excelSheet = "";          int base = 27;          while(n > 0){          if (n % (base - 1) == 0) {excelSheet += 'Z';n /= base;  }          else{          excelSheet += (char)(n %(base - 1)  - 1 + 'A');                  n /= (base - 1);           }                        }          excelSheet = reverse(excelSheet);          return excelSheet;      }}


貌似与26进制的差别就是在26进制数上加1,所以需要每位先减掉,很神奇的规律!!!

public class Solution {      public static String reverse(String string){          String newString = "";          for(int i = string.length() - 1; i>= 0; i--){              newString += string.charAt(i);          }          return newString;      }      public static String convertToTitle(int n) {          String excelSheet = "";          int base = 26;                    while(n > 0){              n--;              char ch = (char)(n % base + 'A');              excelSheet += ch;              n /= base;          }          excelSheet = reverse(excelSheet);          return excelSheet;      }}



0 0