大厂笔试题
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.4 KiB

  1. /*
  2. ipv4是否合法
  3. */
  4. #include <bits/stdc++.h>
  5. using namespace std;
  6. vector<string> split(string s, string spliter) {
  7. vector<string> res;
  8. int i;
  9. //遍历字符串查找spliter
  10. while ((i = s.find(spliter)) && i != s.npos) {
  11. //将分割的部分加入vector中
  12. res.push_back(s.substr(0, i));
  13. s = s.substr(i + 1);
  14. }
  15. res.push_back(s);
  16. return res;
  17. }
  18. bool isIPv4(string IP) {
  19. vector<string> s = split(IP, ".");
  20. if (s.size() != 4)
  21. return false;
  22. for (int i = 0; i < s.size(); i++) {
  23. //不可缺省,有一个分割为零,说明两个点相连
  24. if (s[i].size() == 0)
  25. return false;
  26. //比较数字位数及不为零时不能有前缀零
  27. if (s[i].size() < 0 || s[i].size() > 3 || (s[i][0] == '0' && s[i].size() != 1))
  28. return false;
  29. //遍历每个分割字符串,必须为数字
  30. for (int j = 0; j < s[i].size(); j++)
  31. if (!isdigit(s[i][j]))
  32. return false;
  33. //转化为数字比较,0-255之间
  34. int num = stoi(s[i]);
  35. if (num < 0 || num > 255)
  36. return false;
  37. }
  38. return true;
  39. }
  40. int solve(string IP) {
  41. // write code here
  42. if (IP.size() == 0)
  43. return 0;
  44. if (isIPv4(IP))
  45. return 1;
  46. return 0;
  47. }
  48. int main() {
  49. string str;
  50. cin >> str;
  51. cout << solve(str) << endl;
  52. return 0;
  53. }