1奇偶個數(shù)(5分)
題目內(nèi)容:
你的程序要讀入一系列正整數(shù)數(shù)據(jù)扮饶,輸入-1表示輸入結(jié)束,-1本身不是輸入的數(shù)據(jù)。程序輸出讀到的數(shù)據(jù)中的奇數(shù)和偶數(shù)的個數(shù)蛋济。
輸入格式:
一系列正整數(shù),整數(shù)的范圍是(0,100000)炮叶。如果輸入-1則表示輸入結(jié)束碗旅。
輸出格式:
兩個整數(shù),第一個整數(shù)表示讀入數(shù)據(jù)中的奇數(shù)的個數(shù)镜悉,第二個整數(shù)表示讀入數(shù)據(jù)中的偶數(shù)的個數(shù)祟辟。兩個整數(shù)之間以空格分隔。
輸入樣例:
9 3 4 2 5 7 -1
輸出樣例:
4 2
代碼
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num;
int qcount=0;
int ocount=0;
num = in.nextInt();
while(num != -1) {
if(num % 2==0) {
ocount++;
}
else {
qcount++;
}
num = in.nextInt();
}
System.out.println(qcount+" "+ocount);
}
}
數(shù)字特征值(5分)
題目內(nèi)容:
對數(shù)字求特征值是常用的編碼算法侣肄,奇偶特征是一種簡單的特征值旧困。對于一個整數(shù),從個位開始對每一位數(shù)字編號稼锅,個位是1號叮喳,十位是2號,以此類推缰贝。這個整數(shù)在第n位上的數(shù)字記作x馍悟,如果x和n的奇偶性相同,則記下一個1剩晴,否則記下一個0锣咒。按照整數(shù)的順序把對應(yīng)位的表示奇偶性的0和1都記錄下來侵状,就形成了一個二進(jìn)制數(shù)字。比如毅整,對于342315趣兄,這個二進(jìn)制數(shù)字就是001101。
這里的計(jì)算可以用下面的表格來表示:
數(shù)字 | 3 | 4 | 2 | 3 | 1 | 5 |
---|---|---|---|---|---|---|
數(shù)位 | 6 | 5 | 4 | 3 | 2 | 1 |
數(shù)字奇偶 | 奇 | 偶 | 偶 | 奇 | 奇 | 奇 |
數(shù)位奇偶 | 偶 | 奇 | 偶 | 奇 | 偶 | 奇 |
奇偶一致 | 0 | 0 | 1 | 1 | 0 | 1 |
二進(jìn)制位值 | 32 | 16 | 8 | 4 | 2 | 1 |
按照二進(jìn)制位值將1的位的位值加起來就得到了結(jié)果13悼嫉。
你的程序要讀入一個非負(fù)整數(shù)艇潭,整數(shù)的范圍是[0,100000],然后按照上述算法計(jì)算出表示奇偶性的那個二進(jìn)制數(shù)字戏蔑,輸出它對應(yīng)的十進(jìn)制值蹋凝。
提示:將整數(shù)從右向左分解,數(shù)位每次加1总棵,而二進(jìn)制值每次乘2鳍寂。
輸入格式:
一個非負(fù)整數(shù),整數(shù)的范圍是[0,1000000]情龄。
輸出格式:
一個整數(shù)迄汛,表示計(jì)算結(jié)果。
輸入樣例:
342315
輸出樣例:
13
代碼
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int n1 = num/100000;
int n2 = num/10000-n1*10;
int n3 = num/1000-n1*100-n2*10;
int n4 = num/100-n1*1000-n2*100-n3*10;
int n5 = num/10-n1*10000-n2*1000-n3*100-n4*10;
int n6 = num%10;
int num1,num2,num3,num4,num5,num6;
if(n1!=0&&n1%2==0) {
num1 = 1;
}
else {
num1 = 0;
}
if(n2!=0&&n2%2!=0) {
num2 = 1;
}
else {
num2 = 0;
}
if(n3!=0&&n3%2==0) {
num3 = 1;
}
else {
num3 = 0;
}
if(n4!=0&&n4%2!=0) {
num4 = 1;
}
else {
num4 = 0;
}
if(n5!=0&&n5%2==0) {
num5 = 1;
}
else {
num5 = 0;
}
if(n6!=0&&n6%2!=0) {
num6 = 1;
}
else {
num6 = 0;
}
int res = (int) (num1*Math.pow(2,5)+num2*Math.pow(2,4)+num3*Math.pow(2,3)+num4*Math.pow(2,2)+num5*Math.pow(2,1)+num6*Math.pow(2,0));
System.out.println(res);
}
}