โจทย์
Whole numbers divisible by 2 are even; other whole numbers are odd. A number with a fractional part is neither. Zero is even, and negative integers follow the same rule.
Implement number_parity(number).
Input
number: The number to classify.
Output
Return odd, even, or neither as lowercase text.
เงื่อนไข
−1,000,000 ≤ number ≤ 1,000,000. The input is finite and has at most two decimal places.
ตัวอย่าง
อินพุต:
number = 14
ผลลัพธ์ที่คาดหวัง:
expected = "even"
อินพุต:
double number = 14;
ผลลัพธ์ที่คาดหวัง:
std::string expected = "even";
อินพุต:
double number = 14;
ผลลัพธ์ที่คาดหวัง:
string expected = "even";
คำอธิบาย
14 = 2 × 7, so it is divisible by 2.
อินพุต:
number = 3.5
ผลลัพธ์ที่คาดหวัง:
expected = "neither"
อินพุต:
double number = 3.5;
ผลลัพธ์ที่คาดหวัง:
std::string expected = "neither";
อินพุต:
double number = 3.5;
ผลลัพธ์ที่คาดหวัง:
string expected = "neither";
คำอธิบาย
3.5 has a fractional part, so it is neither an odd nor an even integer.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
First decide whether the input is a whole number, since fractional values are neither odd nor even.
คำใบ้ 2
For whole numbers, parity depends on whether division by 2 leaves a remainder.
คำใบ้ 3
Remember that zero is even, and negative integers follow the same rule as positive ones.
ความซับซ้อนที่คาดหวัง
O(1) time, O(1) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน