参考链接:http://www.cnblogs.com/sshoub/archive/2011/07/29/2121312.html
根据参考链接中的算法,我这样理解
ABCDEF,这个看出一个26进制的数,0<->Z、1<->A、2<->B
题目要求我们将十进制数 和 26进制数进行转换
26进制数字转换成十进制:
注意:越靠近后面的字符,对于的位权越低
如下代码:
public static int AZTonum1(String str){ int r = 0; int p = 0; int n = str.length() ; for(int i = n-1;i>=0;i--){ if(r ==0){ p = str.charAt(i) - 'A' +1; r = 26; }else{ p = p + r *( str.charAt(i) - 'A' +1); r = r * 26; } } return p; }
在上面博客评论中有下面的代码
public static int AZTonum(String str){ int r = 0; for(int i = 0;i<str.length();i++){ r = r * 26 + str.charAt(i) - 'A' +1; } return r; }
这里每次更新需要乘以26来源 大于 26进一位
十进制数转换成26进制
这里就是连除
public static String numToAZ(int num){ if(num == 0) return "Z"; int r = 0; String result=""; while(num!=0){ r = num%26; char ch = ' '; if(r ==0) ch ='Z'; else ch = (char)(r -1 + 'A'); result = ch + result; if(result.charAt(0) == 'Z') num = num/26-1; else num/=26; } return result; }
整体实现代码:
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); String str=null; String[] A; String patternRC = "R[\d]+C[\d]+"; String patternAZ = "[A-Z]+[\d]+"; int num; String res; while(in.hasNext()){ str = in.next(); res =""; num =0; //Rx C y 模式 R23C55 提取 55 转换成26进制 if(str.matches(patternRC)){ int id = str.indexOf('C'); String x = str.substring(1,id); String y = str.substring(id+1); int ynum = Integer.valueOf(y); res = numToAZ(ynum); res = res + x; System.out.println(res); // BC23 提取BC转换成 十进制 }else if(str.matches(patternAZ)){ // System.out.println(str); String x = str.replaceAll("[A-Z]+",""); str = str.replaceAll("[\d]+",""); int y = AZTonum(str); res = "R" + x + "C" + y; System.out.println(res); }else{ System.out.println("输入非法"); } } System.out.println(); } public static int AZTonum(String str){ int r = 0; for(int i = 0;i<str.length();i++){ r = r * 26 + str.charAt(i) - 'A' +1; } return r; } public static int AZTonum1(String str){ int r = 0; int p = 0; int n = str.length() ; for(int i = n-1;i>=0;i--){ if(r ==0){ p = str.charAt(i) - 'A' +1; r = 26; }else{ p = p + r *( str.charAt(i) - 'A' +1); r = r * 26; } } return p; } public static String numToAZ(int num){ if(num == 0) return "Z"; int r = 0; String result=""; while(num!=0){ r = num%26; char ch = ' '; if(r ==0) ch ='Z'; else ch = (char)(r -1 + 'A'); result = ch + result; if(result.charAt(0) == 'Z') num = num/26-1; else num/=26; } return result; } }
程序没有判断输入多少行数据,之间对输入的值进行判断