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());
	}
}

 

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