Advertisement
AmbushedRaccoon

LeetCode Tasks

Jun 23rd, 2021
740
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using std::string;
  5.  
  6. string addBinary(string a, string b) {
  7.     const string& max = a.length() > b.length() ? a : b;
  8.     const string& min = max == a ? b : a;
  9.     char* result_buffer = new char[max.length() + 2];
  10.     memset(result_buffer, 0, max.length() + 2);
  11.     int insert_index = max.length();
  12.     bool extra = false;
  13.     for (int i = max.length() - 1, j = min.length() - 1; i >= 0; i--, j--)
  14.     {
  15.         int current = (max[i] - '0') + (j >= 0 ? min[j] - '0' : 0) + (extra ? 1 : 0);
  16.         extra = current >= 2;
  17.         current %= 2;
  18.         result_buffer[insert_index--] = '0' + current;
  19.     }
  20.     char* res_pointer = result_buffer;
  21.     if (extra)
  22.     {
  23.         res_pointer[insert_index] = '1';
  24.     }
  25.     else
  26.     {
  27.         res_pointer++;
  28.     }
  29.     string result(res_pointer);
  30.     delete[] result_buffer;
  31.     return result;
  32. }
  33.  
  34. bool isPalindrome(int x)
  35. {
  36.     if (x < 0)
  37.     {
  38.         return false;
  39.     }
  40.     char buffer[11];
  41.     memset(buffer, 0, 11);
  42.     int insertIndex = 0;
  43.     while (x > 0)
  44.     {
  45.         buffer[insertIndex++] = x % 10 + '0';
  46.         x /= 10;
  47.     }
  48.     for (int i = 0, j = insertIndex - 1; i < j; i++, j--)
  49.     {
  50.         if (buffer[i] != buffer[j])
  51.         {
  52.             return false;
  53.         }
  54.     }
  55.     return true;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement