Palindrome

My instructor was showing us palindrome numbers today and instead if using string size method she used some division method where last number got extracted. Can anyone give me a hint in how to find if a certain number is palindrome? I thought about dividing the number by ten to extract the last digit, but I can clearly figure out how to compare without using string size.

Last edited on
Are the numbers stored as integers or strings?

Here's one method to get the first and last digit of an integer:

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
#include <iostream>

long long pow( int x , int n )
{
	return( n > 1 ? x * pow( x , n - 1 ) : 1 );
}

int main()
{
	int number = 12345;
	int power_ten = 0;
	int first_digit = 0;
	int last_digit = number; //using last_digit as a temporary variable right now

	while( last_digit > 0 )
	{
    	last_digit /= 10;
    	++power_ten;
	}
	
	//get first digit
	first_digit = number / pow( 10 , power_ten );
	//get last digit
	last_digit = number  % 10;

	
	std::cout << "first digit: " << first_digit << std::endl;
	std::cout << "last digit: " << last_digit << std::endl;
}


This is probably how your teacher did it if she used the divide method.


1
2
	return( n > 1 ? x * pow( x , n - 1 ) : 1 );


Giblit, can you explain to me what this code does here. I know it's similar to if and else, but the expression I can't understand.
Its a c++ operator called the ternary operator.

Basically the pseudo code is like this


(return statement or a variable you are assigning a value to ) (condition to test) ? ( if true return this value ) : (otherwise return this value )

so lets look at my example


The thing I am using the value with is the return statement.
the condition I am using n > 1 //should of been n > 0 I had a typo because x^0 == 1
if n is greater than 1 I am using recursion ( return the value of x * pow( x , n - 1 )
if n is less than or equal to 1 then return 1 //again should have been less than 1 aka 0

Basically it can be rewritten as either of these two:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
long long pow( int x , int n )
{
    if( n > 0 )
        return( x * pow( x , n - 1 );
    return( 1 ); //if x is not greater than 1
}

//or

long long pow( int x , int n  )
{
    int increment = x;
    if( n == 0 )
        return( 1 ); 
    for( int i = 1; i < n; ++i )
        x *= increment;
    return( x );
}


Then it should have been first_digit = number / pow( 10 , power_ten - 1 ) since 1000 = 10^3 not 10^4 I had a brain fart.

Here is somethign to read up on:
http://www.cplusplus.com/articles/1AUq5Di1/
http://www.learncpp.com/cpp-tutorial/34-sizeof-comma-and-arithmetic-if-operators/

*edit also you may use the pow function in the math library if you want. I just didn't feel like it.

**edit
The power_ten in my code is really the amount of digits in the number.
Last edited on
Topic archived. No new replies allowed.