From 4b6b84c4f67caa8b9955120c480000ae524bad8d Mon Sep 17 00:00:00 2001 From: diksha Date: Sun, 29 Oct 2023 18:18:12 +0530 Subject: [PATCH 1/2] Added convert_a_number_to_hexadecimal.cpp --- .../Cpp/convert_a_number_to_hexadecimal.cpp | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 scripts/Cpp/convert_a_number_to_hexadecimal.cpp diff --git a/scripts/Cpp/convert_a_number_to_hexadecimal.cpp b/scripts/Cpp/convert_a_number_to_hexadecimal.cpp new file mode 100644 index 0000000..3bc0603 --- /dev/null +++ b/scripts/Cpp/convert_a_number_to_hexadecimal.cpp @@ -0,0 +1,27 @@ +#include +using namespace std; + +class Solution { +public: + string toHex(int num) { + string hex = "0123456789abcdef"; + string ans; + if(num==0) return "0"; + while (num>0) { + ans = hex[num & 15] + ans; + num >>= 4; + } + if(num<0){ + ans = "00000000"; + num++; + num*=-1; + int i=7; + while(i>=0){ + ans[i] = hex[15 -(num & 15)]; + num >>= 4; + i--; + } + } + return ans; + } +}; \ No newline at end of file From ebe117e2f1d7ff145718c76b3d7cac935ae67af7 Mon Sep 17 00:00:00 2001 From: diksha Date: Sun, 29 Oct 2023 18:21:43 +0530 Subject: [PATCH 2/2] Added 4-Sum_Problem.cpp --- scripts/Cpp/4-Sum_Problem.cpp | 79 +++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 scripts/Cpp/4-Sum_Problem.cpp diff --git a/scripts/Cpp/4-Sum_Problem.cpp b/scripts/Cpp/4-Sum_Problem.cpp new file mode 100644 index 0000000..c2178f8 --- /dev/null +++ b/scripts/Cpp/4-Sum_Problem.cpp @@ -0,0 +1,79 @@ +#include +#include +#include + +class Solution { +public: + std::vector> fourSum(std::vector& nums, int target) { + std::vector> result; + + if (nums.empty()) { + return result; + } + + int n = nums.size(); + std::sort(nums.begin(), nums.end()); + + for (int i = 0; i < n; i++) { + int target_3 = target - nums[i]; + + for (int j = i + 1; j < n; j++) { + int target_2 = target_3 - nums[j]; + int front = j + 1; + int back = n - 1; + + while (front < back) { + int two_sum = nums[front] + nums[back]; + + if (two_sum < target_2) { + front++; + } else if (two_sum > target_2) { + back--; + } else { + std::vector quadruplet(4, 0); + quadruplet[0] = nums[i]; + quadruplet[1] = nums[j]; + quadruplet[2] = nums[front]; + quadruplet[3] = nums[back]; + result.push_back(quadruplet); + + while (front < back && nums[front] == quadruplet[2]) { + front++; + } + + while (front < back && nums[back] == quadruplet[3]) { + back--; + } + } + } + + while (j + 1 < n && nums[j + 1] == nums[j]) { + j++; + } + } + + while (i + 1 < n && nums[i + 1] == nums[i]) { + i++; + } + } + + return result; + } +}; + +int main() { + Solution obj; + std::vector v{1, 0, -1, 0, -2, 2}; + + std::vector> sum = obj.fourSum(v, 0); + std::cout << "The unique quadruplets are" << std::endl; + + for (int i = 0; i < sum.size(); i++) { + for (int j = 0; j < sum[i].size(); j++) { + std::cout << sum[i][j] << " "; + } + std::cout << std::endl; + } + + return 0; +}