題目連結
題意:
輸入一個數字,求他的二進位形式後,輸出1的個數,輸出有固定格式。
解法:
Java的Integer類別中,toBinaryString(int i) 方法可以將數字轉成二進位字串輸出,再逐一讀1的個數即可。
程式(Java):
題意:
輸入一個數字,求他的二進位形式後,輸出1的個數,輸出有固定格式。
解法:
Java的Integer類別中,toBinaryString(int i) 方法可以將數字轉成二進位字串輸出,再逐一讀1的個數即可。
程式(Java):
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
import java.util.*; | |
public class Main { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
int I; | |
while (sc.hasNext()) { | |
int sum = 0; | |
I = sc.nextInt(); | |
if(I == 0) | |
break; | |
String bin = Integer.toBinaryString(I); | |
for (int i = 0 ; i < bin.length(); i++) | |
if (bin.charAt(i) == '1') | |
sum++; | |
System.out.println("The parity of " + bin + " is " + sum + " (mod 2)."); | |
} | |
} | |
} |
留言
張貼留言