[Euler]Problem 36 - Double-base palindromes

本文介绍了一个寻找并计算所有小于一百万且在十进制和二进制下均为回文形式的数字之和的问题。通过使用Java编程语言实现了一个简单的暴力破解算法,最终得出这些数字总和为872187,算法运行耗时133毫秒。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值