add: 220416-CN [cpp]

This commit is contained in:
eat-swap 2022-04-16 22:09:51 +08:00
parent e5549fb0dd
commit a9cc05a3f3
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
3 changed files with 59 additions and 1 deletions

49
cpp/2204/220416-CN.cpp Normal file
View File

@ -0,0 +1,49 @@
#include <cstdio>
#define MIN(a, b) (((a) < (b)) ? (a) : (b))
/**
* 479. Largest Palindrome Product
* Given an integer n, return the largest palindromic integer that can be represented as the product of two n-digits integers. Since the answer can be very large, return it modulo 1337.
*/
class Solution {
private:
static inline constexpr unsigned long long get9(int n) {
unsigned long long ans = 0;
while (n--)
ans = ans * 10 + 9;
return ans;
}
static inline constexpr int getAns(int n) {
auto halfMax = get9(n), halfMin = 1 + get9(n - 1);
for (auto i = halfMax; i >= halfMin; --i) {
unsigned long long iFull = 0;
for (auto j = i; j; j /= 10) {
iFull = 10 * iFull + j % 10;
}
iFull += i * (1 + halfMax);
for (auto j = MIN(halfMax, iFull / halfMin); iFull / j <= halfMax && j >= halfMin; --j) {
if (iFull % j == 0) {
// std::printf("%llu %llu\n", iFull, j);
return iFull % 1337;
}
}
}
return 0;
}
public:
static constexpr int largestPalindrome(int n) {
// const static int ans[] = {-1, 9, 987, 123, 597, 677, 1218, 877, 475};
// return ans[n];
return n == 1 ? 9 : getAns(n);
}
};
int main() {
for (int i = 2; i <= 8; ++i) {
// std::printf("%d\n", getAns(i));
}
return 0;
}

View File

@ -7,6 +7,15 @@ struct TreeNode {
explicit TreeNode(int x, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {} explicit TreeNode(int x, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {}
}; };
/**
* 538. Convert BST to Greater Tree
* Given the root of a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus the sum of all keys greater than the original key in BST.
* As a reminder, a binary search tree is a tree that satisfies these constraints:
* The left subtree of a node contains only nodes with keys less than the node's key.
* The right subtree of a node contains only nodes with keys greater than the node's key.
* Both the left and right subtrees must also be binary search trees.
*/
class Solution { class Solution {
public: public:
static TreeNode* convertBST(TreeNode* root) { static TreeNode* convertBST(TreeNode* root) {

View File

@ -3,4 +3,4 @@ PROJECT(2204)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2204 220416.cpp) ADD_EXECUTABLE(2204 220416-CN.cpp)