您的位置:首页 > 其它

数字和字母混合计算

2015-11-27 12:48 274 查看
工作中遇到一个问题,给出一个邮编段,需要计算出这个邮编段之间的所有邮编。世界上各国的邮编格式都不一样,有的邮编包含数字,字母,空格或者中划线等等,因此邮编格式都是无规律的。例如111222, 1A2B3C, AAABBB, A1BBC2,DD-PP-CC, 11-2-C-D等等

package com;

public class Test2 {

private static String patten = "[0-9A-Z]";

public static void main(String[] args) throws Exception {

String start = "C1G0A0".toUpperCase();

String end = "C9Z9Z9".toUpperCase();

if (start.length() != end.length()) {

System.out.println("起始邮编长度必须跟结束邮编长度一致");

return;

}

if (start.compareTo(end) > 0) {

System.out.println("起始邮编必须小于结束邮编");

return;

}

char[] charArray = start.toCharArray();

String newStart = null;

StringBuilder sb = new StringBuilder();

int i = 1;

long t1 = System.currentTimeMillis();

do {

re(charArray, charArray.length - 1);

newStart = new String(charArray);

sb.append(newStart).append(",");

System.out.println(i + " " + newStart);

i++;

} while (newStart.compareTo(end) < 0);

System.out.println(System.currentTimeMillis() - t1);

}

public static void re(char[] charArray, int i) {

if (! String.valueOf(charArray[i]).matches(patten)) {

re(charArray, i - 1);

}

char newChar = addOne(charArray[i]);

charArray[i] = newChar;

if ((newChar == '0' || newChar == 'A') && i >= 1) {

re(charArray, i - 1);

}

}

public static char addOne(char c) {

if (c >= '0' && c < '9' || c >= 'A' && c < 'Z') {

c += 1;

} else if (c == '9') {

c = '0';

} else if (c == 'Z') {

c = 'A';

}

return c;

}

}

计算结果:592799条数据,耗时8秒钟左右

不知道谁有更好的办法,计算效率高
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: