๐ ๋ฌธ์
๐ ํ์ด (C++)
#include <string>
#include <iostream>
#include <algorithm>
#define MIN_VALUE 0
#define MAX_VALUE 255
using namespace std;
bool has_only_digits(const string s){
// dot(.) == "\000"
return s.find_first_not_of( "0123456789" ) == string::npos && (s != "\000");
}
/* The function returns 1 if
IP string is valid else return 0
You are required to complete this method */
int isValid(string s) {
if (count(s.begin(), s.end(), '.') != 3) return 0;
const string delimiter = ".";
string token;
int dotCount = 3;
// find dot and delete three times!
while (dotCount-- > 0) {
const auto dotIndex = s.find(delimiter);
const auto token = s.substr(0, dotIndex);
// check if has leading '0'
if (token.find("0") != (token.length() - 1) && token.find("0") != string::npos) return 0;
if (!has_only_digits(token)) return 0;
const auto tokenNumber = stoll(token);
// IP address integer range [0,255]
if (MIN_VALUE > tokenNumber || tokenNumber > MAX_VALUE) return 0;
else s.erase(0, dotIndex + 1);
}
if (s.find("0") != (s.length() - 1) && s.find("0") != string::npos) return 0;
if (!has_only_digits(s)) return 0;
const auto tokenNumber = stoll(s);
if (MIN_VALUE > tokenNumber || tokenNumber > MAX_VALUE) return 0;
// all pass
return 1;
}
int main()
{
cout << isValid("1.1.1") << endl;
}
๋๋ ์
javascript๋ฅผ ํ์ด์ธ์ด๋ก ์ ๊ณตํ์ง ์๋ ๋ฐ๋์ ์ธ๋ฉด์ C++๋ก ํ์๋ค.
์ง์ง ์ค ํจ๊ณ ์ถ๋ค.
String์ C++๋ก ํ์ดํ๋ฉด ์ฒ๋ฆฌํ ์ฝ๋๋์ด ๋๋ฌด ๋ง์์ง๋ค.
Geeks For Geeks์์ ์ผ๋ฅธ ๋ค์ํ ์ธ์ด๋ฅผ ์ง์ํ์ผ๋ฉด ํ๋ ๋ฐ๋์ด๋ค.
C++์ split ํจ์์กฐ์ฐจ ์ง์ํ์ง ์์ผ๋
์ด๋ฐ ์์ฃผ ์ฐ์ด๋ ํจ์๋ ๋ฐ๋ก code snippet์ ์ ์ฅํด๋๊ณ ๋ณต๋ถํ๋๊ฒ ๋ซ์ง ์์๊ฐ ์ถ๋ค.
'Algorithm > Algorithm (๋ฌธ์ ํ์ด)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Geeks for Geeks] Insert a node in a BST (0) | 2021.02.23 |
---|---|
[๋ฐฑ์ค 11651] ์ขํ ์ ๋ ฌํ๊ธฐ 2 (0) | 2021.02.21 |
[C++] Iterator (0) | 2021.02.20 |
[Geeks For Geeks] Reverse words in a given String (0) | 2021.02.18 |
[Geeks For Geeks] Reverse a String (0) | 2021.02.18 |