[Euler]Problem 36 - Double-base palindromes

The decimal number, 585 = 10010010012 (binary), is palindromic in both bases.

Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2.

(Please note that the palindromic number, in either base, may not include leading zeros.)


Brute Force!!!

public class Double_BasePalindromes {

	public static void main(String[] args) {
		long before = System.currentTimeMillis();

		new Double_BasePalindromes().calculate();

		System.out.println("elapsed time is : " + (System.currentTimeMillis() - before));
	}

	private void calculate() {
		String baseTwo = "";
		int sum = 0;

		for (int i = 1; i < 1000000; i++) {
			baseTwo = Integer.toBinaryString(i);

			if (isStringPalindromes(String.valueOf(i))) {

				if (isStringPalindromes(baseTwo)) {
					sum += i;
				}

			}

		}

		System.out.println("sum of all numbers is : " + sum);
	}

	private boolean isStringPalindromes(String str) {
		for (int i = 0; i <= str.length() / 2; i++) {

			if (str.charAt(i) != str.charAt(str.length() - 1 - i)) {

				return false;
			}

		}

		return true;
	}

}

console : 
sum of all numbers is : 872187
elapsed time is : 133


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章