java计算任意位水仙花数示例(回文数)

时间:2021-11-01 09:55:36

可计算任意位水仙花数

 

复制代码代码如下:


public static void main(String[] args) {
  int max = 10;
  for (int len = 1; len <= max; len++) {
   System.out.println(getNarc(len, ""));
  }
 }

 

 static StringBuffer strb = new StringBuffer();

 static String getNarc(int len, String start) {
  for (int basenum = 1; basenum <= 9; basenum++) {
   if (len == 2 || len == 1) {
    StringBuffer tmpbuf = new StringBuffer();
    tmpbuf.append(start);
    for (int j = 0; j < len; j++) {
     tmpbuf.append(basenum);
    }
    tmpbuf.append(new StringBuffer(start).reverse().toString());
    strb.append(tmpbuf);
    strb.append("\n");
    // System.out.println(tmpbuf);
   } else if (len > 2) {
    String nextStr = "";
    if (null != start) {
     nextStr = start + basenum;
    } else {
     nextStr = Integer.toString(basenum);
    }
    getNarc(len - 2, nextStr);
   }
  }
  return strb.toString();
 }