Problem 36

问题描述:

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.)

 

解决问题:

java里Integer类可以直接找到整数的二进制表示。

 

 

public class Problem36 {

	public static final int UP = 1000000;
	
	public static boolean IsHuiWen(String number){
		
		int middle = number.length()/2;
		int len = number.length()-1;
		boolean ok = true;
		
		for(int i=0; i<middle; i++){
			if(number.charAt(i)!=number.charAt(len)){
				ok = false;
				break;
			}
			len--;
		}
		
		return ok;
	}
	
	public static int sum(){
		int result = 0;
		
		for(int i=1; i<UP; i++){
			if(i%10==0){
				continue;
			}else{
				if(IsHuiWen(i+"")){
					String binary = Integer.toBinaryString(i);
					if(IsHuiWen(binary)){
						result += i;
					}
				}
			}
		}
		
		return result;
	}
	
	
	public static void main(String[] args){
		System.out.println(sum());
	}
}

 

你可能感兴趣的:(em)