天天看點

P2955 [USACO09OCT]奇數偶數Even? Odd?

奇數偶數Even? Odd?

題目描述

Bessie’s cruel second grade teacher has assigned a list of N (1 <= N <= 100) positive integers I (1 <= I <= 10^60) for which Bessie must determine their parity (explained in second grade as ‘Even… or odd?’). Bessie is overwhelmed by the size of the list and by the size of the numbers. After all, she only learned to count recently.

Write a program to read in the N integers and print ‘even’ on a single line for even numbers and likewise ‘odd’ for odd numbers.

POINTS: 25

Bessie那慘無人道的二年級老師搞了一個有 N 個正整數 I 的表叫Bessie去判斷“奇偶性”(這個詞語意思向二年級的學生解釋,就是“這個數是單數,還是雙數啊?”)。Bessie被那個表的長度深深地震驚到了,竟然跟棟棟的泛做表格一樣多道題!!!畢竟她才剛剛學會數數啊。

寫一個程式讀入N個整數,如果是雙數,那麼在單立的一行内輸出"even",如果是單數則類似地輸出"odd".

輸入輸出格式

輸入格式:

  • Line 1: A single integer: N
  • Lines 2…N+1: Line j+1 contains I_j, the j-th integer to determine even/odd

輸出格式:

  • Lines 1…N: Line j contains the word ‘even’ or ‘odd’, depending on the parity of I_j

輸入輸出樣例

輸入樣例0

2

1024

5931

輸出樣例

even

odd

——摘自洛谷USACO

在洛谷裡面,這道題被評為入門難度。

看到題的第一眼,是否想到了什麼?一個if判斷就能解決的事。然後我就打了代碼:

#include<bits/stdc++.h>
using namespace std;

int a[1000];

int main(){
	int n;
	cin >> n;
	for(int i=1;i<=n;i++){
		cin >> a[i];
	if(a[i]%2==0){
		cout <<"even"<<endl; 
	}else{
		cout << "odd"<<endl;;
	}
}
	
	return 0;
}
           

然而,對了四組。。。

讓我們看看資料範圍——10^60?

那麼,一定是超了範圍罷。。。

于是,一個重要的思路——字元串便可以解決該題。

思路是這樣的:我們開一個char類型的數組,用.size()取其長度,将其減一,取其後兩位,再減’0’把它轉成數字%2,即可求出答案。

#include<bits/stdc++.h>
using namespace std;
string a;
int main(){
	int n;
	cin >> n;
	for(int i=1;i<=n;i++){
		cin >> a;
		if((a[a.size()-1]-'0')%2==0){
		cout << "even"<<endl;
		}else{
		 cout << "odd"<<endl;
	}
	}

	return 0;
}