close
題目概要:
把所輸入的數字轉成2進位,並計算有多少個1。
解題方向:
Solution1: 直接使用Java提供的API(Integer.toBinaryString),因為它回傳String,所以可以直接解析字串,並計算有幾個1。再依題目需求印出答案即可。
Solution2: 讀入數字後,自己寫一個短除法的式子,用字串儲存餘數(binary),計算有幾個1。再依題目需求印出答案即可。
程式碼:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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)."); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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)."); | |
} | |
} | |
} |
文章標籤
全站熱搜