AlenAntonelli

Reverse and Add

May 30th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.60 KB | None | 0 0
  1. /// https://trello.com/c/R1Trslg7/70-uva-10018-reverse-and-add
  2. /// https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=959
  3. #include <iostream>
  4. #include <string>
  5. #include <algorithm>
  6. using namespace std;
  7.  
  8. string suma (string a, string b)
  9. {
  10.     long may = max( a.size(), b.size() );
  11.    
  12.     reverse( a.begin(), a.end() );
  13.     reverse( b.begin(), b.end() );
  14.    
  15.     for(long i=a.size(); i<may; i++) ///que me haga max-x.size() de operaciones
  16.         a.push_back('0');
  17.     for(long i=b.size(); i<may; i++) ///que me haga max-x.size() de operaciones
  18.         b.push_back('0');
  19.        
  20.     bool ac = false;
  21.     string c;
  22.    
  23.     for(long i=0; i<a.size(); i++)
  24.     {
  25.         long A = a[i]-'0';
  26.         long B = b[i]-'0';
  27.         long C = A+B+ac;
  28.  
  29.         ac = C/10;
  30.         c.push_back( (C)%10 +'0' );
  31.     }
  32.     if(ac)
  33.         c.push_back('1');
  34.    
  35.     reverse(c.begin(), c.end());
  36.    
  37.     return c;
  38. }
  39.  
  40. bool es_palindromo(string s)
  41. {
  42.     bool palindromo = true;
  43.    
  44.     for(long i=0; i<s.size() && palindromo; i++)
  45.         if(s[i]!=s[s.size()-i-1])
  46.             palindromo = false;
  47.            
  48.     return palindromo;
  49. }
  50.  
  51. void reverse_and_add(string s)
  52. {
  53.     long c=0;
  54.    
  55.     while( !es_palindromo(s) )
  56.     {
  57.         c++;
  58.         string aux = s;
  59.         reverse( aux.begin(), aux.end() );
  60.         s = suma(s,aux);
  61.     }
  62.    
  63.     cout<<c<<" "<<s<<endl;
  64. }
  65.  
  66. int main()
  67. {
  68.     long n;
  69.     string s;
  70.    
  71.     cin>>n;
  72.     for (long i=0; i<n; i++)
  73.     {
  74.         cin>>s;
  75.         reverse_and_add(s);
  76.     }
  77.  
  78.     return 0;
  79. }
Advertisement
Add Comment
Please, Sign In to add comment