我如何为竞争性编程使用测试用例?CodeChef c++



我刚刚开始在CodeChef上进行竞争性编程,我正在处理这个挑战,在大多数情况下,它是有效的,但我不确定如何实现测试用例。我已经看到人们使用while循环和递减T的解决方案,我尝试过,但我没有运气。

下面是问题语句:

问题:如果给定一个整数N。写一个程序求出这个数的首尾数字之和

Input:第一行包含一个整数T,测试用例的总数。然后按T行排列,每行包含一个整数n。

#include <iostream>
#include <string>
using namespace std;
// First and Last Digit
int main() {
// your code goes here
// 1. T for test cases
int T;
// 2. Get input from N;
int N;
cout<<"Enter number: ";
cin>>N;
// 3. Convert int to string
string convert = to_string(N);
// 4. Get index [0] and [string length - 1] 
string first;
string last;
for(int i = 0; i < convert.length(); i++)
{
first = convert[0];
last = convert[convert.length() - 1];
}
// 5. convert single digit to int
int firstDigit = stoi(first);
int lastDigit = stoi(last);
// 6. add both numbers
int total = firstDigit + lastDigit;
// 7. output both numbers
cout<<total;
return 0;
}

竞争性编程很有趣!这是编写紧凑和快速代码的好练习。

不要被"测试用例"这个术语所迷惑,它只是"数字"的一个花哨的名字。首先读取T,然后读取N,循环T次。

有点像这样:

size_t T;
std::cin >> T;
while (T--)  // loop T times
{
std::string N;  // read N as a string
std::cin >> N;  // this will skip all whitespace and only 
// give us the good stuff. n is a whitespace.
// ...
auto sum = (N.front() - '0') + (N.back() - '0');
// ...
}

相关内容

最新更新