[Java] Dual Palindromes

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

public class dualpal {
    
    

	private String radix = "0123456789";
	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, int b) {
    
    
		Stack<Character> stack = new Stack<>();
		do {
    
    
			int r = num % b;
			num = num / b;
			stack.push(radix.charAt(r));
		} while (num != 0);

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

	public dualpal() throws IOException {
    
    
		// Use BufferedReader rather than RandomAccessFile; it's much faster
		BufferedReader f = new BufferedReader(new FileReader("dualpal.in"));
		PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("dualpal.out")));

		// Use StringTokenizer vs. readLine/split -- lots faster
		StringTokenizer st = new StringTokenizer(f.readLine());

	    int N = Integer.parseInt(st.nextToken());    // first integer
	    int S = Integer.parseInt(st.nextToken());    // second integer
	    while (N > 0) {
    
    
	    	++S;
	    	int count = 0;
	    	for (int b = 2; b <= 10; b++) {
    
    
	    		if (isPalindromic(convert2B(S, b))) {
    
    
	    			count++;
	    		}
	    		if (count >= 2) {
    
    
	    			out.println(S);
	    			N--;
	    			break;
	    		}
	    	}
	    }
	    out.close();                                  // close the output file
	}
	
	public static void main (String [] args) throws IOException {
    
    
		new dualpal();
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_41714373/article/details/111996614