【发布时间】:2016-09-29 23:09:38
【问题描述】:
我现在正在处理 CodeEval 上的一项简单挑战。您需要逐行从文件中获取输入,并且每行包含由管道分隔的十六进制数和二进制数。目的是将左边所有的十六进制数相加,右边的二进制数相加,并测试哪个和更大。如果右侧(二进制边)大于或等于十六进制边,则打印“True”,否则打印“False”。示例行是“5e 7d 59 | 1101100 10010101 1100111”,输出为真,因为右侧大于左侧。我的代码在我的计算机上打印了正确的输出,但在 CodeEval 上,没有结果输出,我的分数为零。没有列出任何错误。有没有我看不到的问题?
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <cstdlib>
#include <math.h>
using namespace std;
fstream myFile;
string line;
vector<string> panNums;
int sum1, sum2;
int toDec(string s);
int main(int argc, char *argv[])
{
//open the file
// get numbers by line
myFile.open(argv[1]);
while(getline(myFile, line))
{
//cout << line << endl;
istringstream mystream(line);
string nums;
// read in each number into string nums one by one
// then add that number to the vector that was created
while(mystream)
{
mystream >> nums;
panNums.push_back(nums);
}
bool afterSep = false;
sum1 = 0;
sum2 = 0;
for(int i = 0; i < panNums.size() - 1; i++)
{
stringstream stream;
if(panNums.at(i) == "|")
{
sum1 = sum2;
sum2 = 0;
afterSep = true;
i++;
}
// if true, do stuff
if(afterSep)
{
// deals with the binary side
sum2 += toDec(panNums.at(i));
}
// if false, do other stuff
else
{
// deals with the hexidecimal side
istringstream f(panNums.at(i));
int temp;
// reading hex number into int(AKA converting to int)
f >> hex >> temp;
sum2 += temp;
}
}
// cout << "sum1 " << sum1 << endl;
// cout << "sum2 " << sum2 << endl;
if(sum2 >= sum1)
{
cout << "True" << endl;
}
else
{
cout << "False" << endl;
}
// clear the current vector in order to exclusively have the next line of text stored
panNums.clear();
}
}
int toDec(string s)
{
int num = 0;
int i = s.size() - 1;
// starts at index 0
// which is really the 2^6 or however big the binary number is
for(int a = 0; a < s.size(); a++)
{
if(s.substr(i, 1) == "1")
{
num += pow(2, a);
}
i--;
}
// cout << num << endl;
return num;
}
【问题讨论】:
-
我不熟悉 CodeEval,但这种网站通常通过标准输入而不是文件来提供输入。
-
是的,这通常也是我在其他编码网站上看到的,但 CodeEval 使用文件路径作为输入。
-
#include <string>— 你似乎依赖于它被其他东西拉进来,这取决于平台。 -
将
num += pow(2,a);更改为num += 1 << a;。pow函数浪费了 2 的幂和平方。左移更简单,大多数处理器都有执行操作的指令,而不是调用函数来执行此操作。 -
将
if (s.substr(i,1) == "1")替换为if (s[i] == '1')。您不需要提取 1 个字符的子字符串。耗时太长。只看1个字符。该字符串可以被视为一个字符数组。