1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
#include <iostream>
#include <concepts>
#include <type_traits>
#include <ranges>
#include <algorithm>
#include <string>
#include <list>
template < std::unsigned_integral INT > INT reverse( INT n, int rev_so_far = 0 )
{
if( n == 0 ) return rev_so_far ;
rev_so_far *= 10 ;
rev_so_far += n%10 ;
return reverse( n/10, rev_so_far ) ;
}
template < std::unsigned_integral INT >
bool is_palindrome( INT n ) { return n == reverse(n) ; }
template < std::signed_integral INT >
bool is_palindrome( INT n ) { return n < 0 ? false : is_palindrome( std::make_unsigned_t<INT>(n) ) ; }
template < std::ranges::random_access_range RANGE >
bool is_palindrome( const RANGE& range )
{
const auto n = std::ranges::size(range) / 2 ;
return std::equal( std::ranges::begin(range), std::ranges::begin(range) + n, std::ranges::rbegin(range) ) ;
}
template < std::ranges::bidirectional_range RANGE >
bool is_palindrome( const RANGE& range )
{
return std::equal( std::ranges::begin(range), std::ranges::end(range), std::ranges::rbegin(range) ) ;
}
// usage:
int main()
{
const long array[] { 1, 2, 3, 4, 4, 3, 2, 1 } ;
std::cout << std::boolalpha << is_palindrome( 12344321 ) << '\n'
<< is_palindrome(array) << '\n'
<< is_palindrome( std::string("123454321") ) << '\n'
<< is_palindrome( std::list<std::string> { "abc", "def", "ghi", "def", "abc" } ) << '\n' ;
}
|