From 8358b4cf56fb5239f9322b93e044697edcd1eca1 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Sun, 3 Jul 2022 23:56:50 +0800 Subject: [PATCH] add: 220703-CN --- cpp/2207/220703-CN.cpp | 23 +++++++++++++++++++++++ cpp/2207/CMakeLists.txt | 2 +- 2 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 cpp/2207/220703-CN.cpp diff --git a/cpp/2207/220703-CN.cpp b/cpp/2207/220703-CN.cpp new file mode 100644 index 0000000..141395f --- /dev/null +++ b/cpp/2207/220703-CN.cpp @@ -0,0 +1,23 @@ +#include +#include +#include + +/** + * 556. Next Greater Element III + * Given a positive integer n, find the smallest integer which has exactly the same digits existing in the integer n and is greater in value than n. If no such positive integer exists, return -1. + * Note that the returned integer should fit in 32-bit integer, if there is a valid answer but it does not fit in 32-bit integer, return -1. + */ + +class Solution { +public: + static int nextGreaterElement(int n) { + auto s = std::to_string(n); + if (!std::next_permutation(s.begin(), s.end())) + return -1; + try { + return std::stoi(s); + } catch (const std::out_of_range& e) { + return -1; + } + } +}; diff --git a/cpp/2207/CMakeLists.txt b/cpp/2207/CMakeLists.txt index 3f2fa33..bdd99d3 100644 --- a/cpp/2207/CMakeLists.txt +++ b/cpp/2207/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2207) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2207 220702.cpp) +ADD_EXECUTABLE(2207 220703-CN.cpp)