Advertisement
KennasSticky

p36_cringe

Mar 19th, 2022
647
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #include <chrono>
  3.  
  4. using namespace std;
  5.  
  6. long long total = 1;
  7.  
  8. int toDec(string s) {
  9.     int ans = 0;
  10.     int len = s.size();
  11.     for (int i = len - 1; i >= 0; i--) {
  12.         int val = (s[i] == '0') ? 0 : pow(2, len - i - 1);
  13.         ans += val;
  14.     }
  15.     return ans;
  16. }
  17.  
  18. bool isPalindrome(string t) {
  19.     int len = t.size();
  20.     for (int i = 0; i <= len / 2; i++) {
  21.         if (t[i] != t[len - 1 - i]) return 0;
  22.     }
  23.     return 1;
  24. }
  25.  
  26. void check(string s) {
  27.  
  28.     string temp, a, b;
  29.  
  30.     temp = s;
  31.     a = s;
  32.     b = s;
  33.    
  34.     reverse(s.begin(), s.end());
  35.    
  36.     temp = temp + s;
  37.     a = a + "0" + s;
  38.     b = b + "1" + s;
  39.  
  40.     // convert to decimal
  41.     int d1 = toDec(temp);
  42.     int d2 = toDec(a);
  43.     int d3 = toDec(b);
  44.  
  45.     if (d1 < 1000000 && isPalindrome(to_string(d1))) {
  46.         // cout << d1 << " : " << temp << "\n";
  47.         total += d1;
  48.     }
  49.  
  50.     if (d2 < 1000000 && isPalindrome(to_string(d2))) {
  51.         // cout << d2 << " : " << a << "\n";
  52.         total += d2;
  53.     }
  54.  
  55.     if (d3 < 1000000 && isPalindrome(to_string(d3))) {
  56.         // cout << d3 << " : " << b << "\n";
  57.         total += d3;
  58.     }
  59. }
  60.  
  61. void gen(string s) {
  62.     if (!s.empty()) {
  63.         // process
  64.         check(s);
  65.     }
  66.  
  67.     if (s.size() == 10) return; // base case
  68.  
  69.     gen( s + "1");
  70.     gen( s + "0");
  71.  
  72. }
  73.  
  74. int main() {
  75.  
  76.     auto start = std::chrono::steady_clock::now();
  77.  
  78.     gen("1");
  79.  
  80.     auto stop = std::chrono::steady_clock::now();
  81.    
  82.     auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>((stop - start) / 1000);
  83.    
  84.     cout << "Time taken by function: " << duration.count() << " nanoseconds" << endl;
  85.  
  86.     cout << total << "\n";
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement