描述
When provided with a number between 0-9, return it in words.
Input :: 1
Output :: “One”.
If your language supports it, try using a switch statement.
这个题很简单,但人们不按套路出牌
测试用例
#include <string>
#include <random>
Describe(Switch_it_Up)
{
It(Fixed_tests)
{
Assert::That(switch_it_up(0), Equals("Zero"));
Assert::That(switch_it_up(1), Equals("One"));
Assert::That(switch_it_up(2), Equals("Two"));
Assert::That(switch_it_up(3), Equals("Three"));
Assert::That(switch_it_up(4), Equals("Four"));
Assert::That(switch_it_up(5), Equals("Five"));
Assert::That(switch_it_up(6), Equals("Six"));
Assert::That(switch_it_up(7), Equals("Seven"));
Assert::That(switch_it_up(8), Equals("Eight"));
Assert::That(switch_it_up(9), Equals("Nine"));
}
std::string solution(int number) {
switch(number) {
case 0:
return "Zero";
case 1:
return "One";
case 2:
return "Two";
case 3:
return "Three";
case 4:
return "Four";
case 5:
return "Five";
case 6:
return "Six";
case 7:
return "Seven";
case 8:
return "Eight";
case 9:
return "Nine";
default:
return "ejini战神's solution!!!";
}
}
int generate_random_num(){
std::random_device engn;
std::uniform_int_distribution<> n_pick(0, 9);
int n = n_pick(engn);
return n;
}
It(random_tests){
for(size_t i = 0; i < 100; i++) {
int n = generate_random_num();
Assert::That(switch_it_up(n), Equals(solution(n)));
}
}
};
解答
一般方法
#include <bits/stdc++.h>
using namespace std;
string switch_it_up(int number)
{
switch (number) {
case 0: return "Zero";
case 1: return "One";
case 2: return "Two";
case 3: return "Three";
case 4: return "Four";
case 5: return "Five";
case 6: return "Six";
case 7: return "Seven";
case 8: return "Eight";
case 9: return "Nine";
default: return "";
}
}
vector写法
#include <string>
#include <vector>
std::string switch_it_up(int number){
return std::vector<std::string>{"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"}[number];
}
除了在分配vector时会占用一些时间空间,执行的速度上应该比switch快吧,还有数组的写法,类似。
map
#include <string>
#include <map>
std::map<int, std::string> m = {{0, "Zero"}, {1, "One"},
{2, "Two"}, {3, "Three"},
{4, "Four"}, {5, "Five"},
{6, "Six"}, {7, "Seven"},
{8, "Eight"}, {9, "Nine"}};
std::string switch_it_up(int number){
return m[number];
}
和vector 做法差不多