close

題目概要:

把所輸入的數字轉成2進位,並計算有多少個1。

解題方向:

Solution1: 直接使用Java提供的API(Integer.toBinaryString),因為它回傳String,所以可以直接解析字串,並計算有幾個1。再依題目需求印出答案即可。

Solution2: 讀入數字後,自己寫一個短除法的式子,用字串儲存餘數(binary),計算有幾個1。再依題目需求印出答案即可。

程式碼:

//Java-solution1
import java.util.Scanner;
class uva10931{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int num;
while(sc.hasNext() && (num=sc.nextInt())!=0){
String st=Integer.toBinaryString(num);
//計算有多少1
int count=0;
for(int i=0;i<st.length();i++){
if(st.charAt(i)=='1') count++;
}
//結果輸出
System.out.println("The parity of "+st+" is "+count+" (mod 2).");
}
}
}
view raw uva10931.java hosted with ❤ by GitHub

//Java-solution2
import java.util.Scanner;
class uva10931{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int num;
while((num=sc.nextInt())!=0){
//短除法,自生成binary
String st="";
while(true){
if(num==1){
st="1"+st;
break;
}
st=(char)num%2+st;
num=num/2;
}
//計算有幾個1
int count=0;
for(int i=0;i<st.length();i++){
if(st.charAt(i)=='1') count++;
}
//答案輸出
System.out.println("The parity of "+st+" is "+count+" (mod 2).");
}
}
}
view raw uva10931.java hosted with ❤ by GitHub

arrow
arrow
    文章標籤
    Java
    全站熱搜
    創作者介紹
    創作者 a7069810 的頭像
    a7069810

    紀錄自己的程式人生

    a7069810 發表在 痞客邦 留言(0) 人氣()