Java语言高分悬赏:怎么实现36进制计数法的累加,要求能带进位算法的
思路就是:按照十进制的加法方法,满36向前进一位,这里有一篇比较详细的实现文章,可以参考:https://www.jianshu.com/p/a98caf83e67b
说句实话,简书的文章排版比这个网站好呢。
封装了一个类,参考一下吧
public class MyDigit {
static final char[] dig="0123456789abcdefghijklmnopqrstuvwxyz".toCharArray();
private String value;
public MyDigit(String value) { //非法字符一律当0处理
if (value==null) this.value = "0";
else this.value = value.replaceAll("[^0-9a-zA-Z]+", "0");
}
public MyDigit plus(MyDigit ts) {
return plus(ts.value);
}
public MyDigit plus(String value) {
value = value.replaceAll("[^0-9a-zA-Z]+", "0");
return plus(value.toCharArray());
}
protected MyDigit plus(char[] v) {
StringBuilder buf = new StringBuilder();
char[] c = this.value.toCharArray();
int i=0,j=0,n=0;
for (i=c.length-1, j=v.length-1; i>=0&&j>=0; i--,j--) {
if ((c[i]>='A' && c[i]<='Z') ||
(c[i]>='a' && c[i]<='z'))
c[i] = (char)(c[i]%32 + 9);
else
c[i] -= '0';
if ((v[j]>='A' && v[j]<='Z') ||
(v[j]>='a' && v[j]<='z'))
v[j] = (char)(v[j]%32 + 9);
else
v[j] -= '0';
n += (c[i] + v[j]);
buf.append(dig[n%36]);
n /= 36; //保留进位
}
for (;j>=0;j--) {
if ((v[j]>='A' && v[j]<='Z') ||
(v[j]>='a' && v[j]<='z'))
v[j] = (char)(v[j]%32 + 9);
else
v[j] -= '0';
n += v[j];
buf.append(dig[n%36]);
n /= 36;
}
for (;i>=0; i--) {
if ((c[i]>='A' && c[i]<='Z') ||
(c[i]>='a' && c[i]<='z'))
c[i] = (char)(c[i]%32 + 9);
else
c[i] -= '0';
n += c[i];
buf.append(dig[n%36]);
n /= 36;
}
if (n>0) {
buf.append(dig[n]);
}
this.value = buf.reverse().toString();
return this;
}
public String getValue() {
return this.value;
}
public String toString() {
return this.value;
}
public static void main(String[] args) {
try {
MyDigit t1 = new MyDigit("abc");
t1 = t1.plus("1234");
System.out.println(t1);
} catch (Throwable e) {
e.printStackTrace();
}
}
}