最近,我找到了/ r / dailyprogrammer,并且做了一个挑战:
https://www.reddit.com/r/dailyprogrammer/comments/38yy9s/20150608_challenge_218_easy_making_numbers/
使数字回文很简单,但是Java毕竟是一种面向对象的语言,因此我决定使用对象。这是到目前为止我得到的:
import java.math.*;
public class Lychrel {
BigInteger in;
BigInteger out;
int steps;
boolean isLychrel;
public String get(BigInteger n) {
Lychrel L = make(n);
String S;
if (L.isLychrel) {
return "NUMBER " + L.in + " IS A LYCHREL NUMBER!";
}
if (L.steps == 0) {
return "NUMBER " + L.in + " IS ALREADY PALINDROMIC! (NO STEPS NEEDED)";
}
if (L.steps == 1) {
S = "STEP";
} else {
S = "STEPS";
}
return "NUMBER " + L.in + " GETS PALINDROMIC IN " + L.steps + " " + S + " (" + L.out + ")";
}
private static String palindrome(String str) {
return new StringBuilder(str).reverse().toString();
}
private static boolean isPalindrome(String x) {
return x.equals(palindrome(x));
}
private static Lychrel make(BigInteger n) {
Lychrel lychrel = new Lychrel();
BigInteger input = n;
lychrel.in = input;
final int MAX_STEPS = 100;
for (int steps = 0; ; steps++) {
String N = String.valueOf(n);
if (isPalindrome(N)) {
lychrel.steps = steps;
lychrel.isLychrel = false;
lychrel.out = new BigInteger(N);
break;
}
String N_reversed = palindrome(N);
n = n.add(new BigInteger(N_reversed));
if (steps > MAX_STEPS) {
lychrel.steps = 0;
lychrel.isLychrel = true;
lychrel.out = input;
break;
}
}
return lychrel;
}
}
class Main {
public static void main(String args[]) {
Lychrel x = new Lychrel();
System.out.println(x.get(new BigInteger("179")));
}
}
它的效果非常好,但是我对创建实际的
Lychrel
对象有些困惑。是否可以做:
BigInteger n = new BigInteger("120");
Lychrel x = new Lychrel(n);
System.out.println(x);
而不是上面的东西? :
BigInteger n = new BigInteger("120");
Lychrel x = new Lychrel();
System.out.println(x.get(n));
在我看来,我仍然还没有掌握OOP的基本概念...
用新实例调用新对象的方法的最简单方法是:
Lychrel x = new Lychrel().get(new BigInteger("120"));
如果要打印结果:
System.out.println(new Lychrel().get(new BigInteger("120")));
这样,Java不会将引用分配给变量(
n
和
x
),但除此之外,它会做完全相同的事情。
我是一名优秀的程序员,十分优秀!