LinkedIn Interview Question

Parse the IP in a file, actually, it is not difficult

Interview Answers

Anonymous

Mar 13, 2014

Solution in C++: using namespace std; #include #include #include #include typedef unsigned int uint; static uint ip2num(const char* buf) { uint res = 0, b = 0; for (; *buf;) { char c = *buf++; if (c == '.') { res = (res << 8) + b; b = 0; } else if (isdigit(c)) { b = b * 10 + (c - '0'); } else return (res << 8) + b; } return (res << 8) + b; } int main(int argc, char** argv) { if (argc < 2) { cerr << "Missing file argument" << endl; exit(1); } ifstream is(argv[1]); if (!is) { cerr << "Error opening file" << endl; exit(1); } for (;;) { char buf[32]; is.getline(buf, sizeof(buf)); if (!is) break; cout << "ip " << buf << " decimal represenation is " << ip2num(buf) << endl; } return 0; }

2

Anonymous

Aug 8, 2014

Quick guess in Perl open "filename.txt" || die while : $string ~= /\d+\.\d+\.\d+\.\d+/ print $string

1