[Java] Palindromic Squares

/* Use the slash-star style comments or the system won't see your
   identification information */
/*
ID: lincans1
LANG: JAVA
TASK: palsquare
*/
import java.io.*;
import java.util.*;

public class palsquare {
    
    
	private String string = "0123456789ABCDEFGHIJK";
	private int B;

	private boolean isPalindromic(String num) {
    
    
		for (int i = 0, n = num.length()/2; i < n; i++) {
    
    
			if (num.charAt(i) != num.charAt(num.length() - 1- i)) {
    
    
				return false;
			}
		}
		return true;
	}

	private String convert2B(int num) {
    
    
		Stack<Character> stack = new Stack<>();
		do {
    
    
			int r = num % B;
			num = num / B;
			stack.push(string.charAt(r));
		} while (num != 0);

		StringBuilder b = new StringBuilder();
		while (!stack.isEmpty()) {
    
    
			b.append(stack.pop());
		}
		return b.toString();
	}

	public palsquare() throws IOException {
    
    
		// Use BufferedReader rather than RandomAccessFile; it's much faster
		BufferedReader f = new BufferedReader(new FileReader("palsquare.in"));
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("palsquare.out")));
		
		this.B = Integer.parseInt(f.readLine());
		for (int i = 1; i <= 300; i++) {
    
    
			String square = convert2B(i * i);
			if (isPalindromic(square)) {
    
    
				out.println(convert2B(i) + " " + square);
			}
		}
	    out.close();                                  // close the output file
	}
	
	public static void main (String [] args) throws IOException {
    
    
		new palsquare();
	}
}

Guess you like

Origin blog.csdn.net/weixin_41714373/article/details/111994855