From bcf02d6f9fc362da4cb3b20609b0e28f3b0071fe Mon Sep 17 00:00:00 2001 From: Lam Haoyin Date: Fri, 25 Feb 2022 22:23:16 +0800 Subject: [PATCH] add: 220225 [cpp] --- cpp/2202/220225.cpp | 46 +++++++++++++++++++++++++++++++++++++++++ cpp/2202/CMakeLists.txt | 2 +- 2 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 cpp/2202/220225.cpp diff --git a/cpp/2202/220225.cpp b/cpp/2202/220225.cpp new file mode 100644 index 0000000..34f2a7d --- /dev/null +++ b/cpp/2202/220225.cpp @@ -0,0 +1,46 @@ +#include +#include +#include + +inline constexpr int sgn(int x) { return x ? (x > 0 ? 1 : -1) : 0; } + +class Version { +private: + std::vector revisions; +public: + explicit Version(std::vector v = {1}) : revisions(std::move(v)) {} + + explicit Version(const std::string& str) { + int pos = -1; + revisions.clear(); + const char* s = str.c_str(); + + do { + int x = std::atoi(s + pos + 1); + revisions.push_back(x); + } while (-1 != (pos = str.find('.', pos + 1))); + } + + int compareTo(const Version& rhs) const { + int m = this->revisions.size(), n = rhs.revisions.size(); + int k = std::max(m, n); + for (int i = 0; i < k; ++i) + if (sgn((i < m ? this->revisions[i] : 0) - (i < n ? rhs.revisions[i] : 0))) + return sgn((i < m ? this->revisions[i] : 0) - (i < n ? rhs.revisions[i] : 0)); + return 0; + } +}; + +class Solution { +public: + static int compareVersion(const std::string& version1, const std::string& version2) { + return Version(version1).compareTo(Version(version2)); + } +}; + +int main() { + std::cout << Solution::compareVersion("1.01", "1.001"); + std::cout << Solution::compareVersion("1.0", "1.0.0"); + std::cout << Solution::compareVersion("0.1", "1.1"); + return 0; +} diff --git a/cpp/2202/CMakeLists.txt b/cpp/2202/CMakeLists.txt index 7b782db..0bc6028 100644 --- a/cpp/2202/CMakeLists.txt +++ b/cpp/2202/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2202) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2202 220225-CN.cpp) +ADD_EXECUTABLE(2202 220225.cpp)