最後更新於 2021 年 5 月 21 日
題目原文:https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1872
題目概要:將Input轉為二進制,並輸出該二進制包含的1個數。
需要使用到 Integer.toBinaryString()方法
該方法可以將輸入的int值轉化成二進制形式並返回這個二進制數的字符串。
Sample Input
1
2
10
21
0
Sample Output
The parity of 1 is 1 (mod 2).
The parity of 10 is 1 (mod 2).
The parity of 1010 is 2 (mod 2).
The parity of 10101 is 3 (mod 2).
程式碼
import java.util.*; public class main{ public static void main(String[] args) { Scanner sc=new Scanner(System.in); int num; while(sc.hasNext()&&(num=sc.nextInt())!=0){ String str = Integer.toBinaryString(num); int count=0; for(int j=0;j<str.length();j++){ if(str.charAt(j)=='1'){ count++; } } System.out.println("The parity of "+(str)+" is "+count+" (mod 2)."); } } };
Latest posts by pluto (see all)
- React 那些好看、有趣、實用的函式庫、組件庫推薦(2) - 2022 年 6 月 26 日
- 解決 preact-router 資源請求路徑錯誤的問題 - 2022 年 6 月 24 日
- [楓之谷私服] 潮流轉蛋機 NPC 腳本優化 - 2022 年 6 月 19 日