C solution: check if x equals its reverse


  • 0
    S

    Here is my C code submitted successfully.

    #include <stdio.h>
    #include <stdbool.h>
    #include <math.h>
    
    // 9. Palindrome Number
    // Determine whether an integer is a palindrome. Do this without extra space.
    // https://leetcode.com/problems/palindrome-number/
    
    // Algorithm:
    // get reverse of x => x'
    // check whether x == x'
    // 		if yes, return true
    //      else, return false
    
    // Assume x >= 0
    // Assume no '+'' or '-'' sign at front
    // Assume no space
    
    // base case: x < 10, return true
    
    bool isPalindrome(int x) {
    	// Base case
    	if (x < 0) return false;	// negative number is NOT palindromic
    	if (x < 10 && x >= 0) return true;	// single digit is palindrome
    
    	// Get reverse of x
    	int y = 0, n = x;	
    	while(n) {
    		y = y * 10 + n % 10;
    		n /= 10;
    	}
    
    	// if original x equals to its reverse, it is palindrome
    	if (x == y) return true;
    
    	return false;
    }
    
    int main() {
    	int x = -2147447412;
    	char *result = isPalindrome(x) > 0 ? "true" : "false";
    	printf("*%d* is palindrome: %s\n", x, result);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.