CodeWars刷题笔记
发布时间
阅读量:
阅读量
1、Create Phone Number
Define a function named 'phone_number_generator' that takes as input an array consisting of exactly ten integers, each within the range of zero through nine inclusive. The function will process this array and return a formatted string representing a telephone number based on these integer values.
using arr = int [10];
Describe(CreatePhoneNumber) {
It(BasicTests) {
Assert::That(createPhoneNumber(arr{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}), Equals("(123) 456-7890"));
Assert::That(createPhoneNumber(arr{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}), Equals("(111) 111-1111"));
Assert::That(createPhoneNumber(arr{1, 2, 3, 4, 5, 6, 8, 8, 0, 0}), Equals("(123) 456-8800"));
Assert::That(createPhoneNumber(arr{0, 2, 3, 0, 5, 6, 0, 8, 9, 0}), Equals("(023) 056-0890"));
Assert::That(createPhoneNumber(arr{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}), Equals("(000) 000-0000"));
}
};
AC代码:
#include <string>
std::string createPhoneNumber(const int arr [10]){
//your code here
/*普通做法
std::string res="(";
for(unsigned i=0;i<10;i++)
{
if(i==3)res+=") ";
if(i==6)res+="-";
res+=arr[i]+'0';
}
*/
std::string res="(...) ...-....";//格式化字符串,不用管下标
for(unsigned i=0,j=0;i<res.length();i++)
{
if(res[i]=='.')
{
res[i]='0'+arr[j++];
}
}
return res;
}
2、Even or Odd
Define a function that accepts when given an integer, returning either "Even" if the number is even or "Odd" if it is odd.
Describe(even_or_odd_method)
{
It(basic_tests)
{
Assert::That(even_or_odd(2), Equals("Even"));
Assert::That(even_or_odd(1), Equals("Odd"));
Assert::That(even_or_odd(0), Equals("Even"));
Assert::That(even_or_odd(7), Equals("Odd"));
Assert::That(even_or_odd(-1), Equals("Odd"));
}
};
#include <string>
#include<cmath>
using namespace std;
std::string even_or_odd(int number)
{
std::string res= abs(number)%2==0 ? "Even":"Odd";//取绝对值
return res;
}
全部评论 (0)
还没有任何评论哟~
