Problem 9: palindrome number

This commit is contained in:
Ivan R. 2022-11-19 17:43:23 +05:00
parent b63e4594d9
commit 3b71bbbca8
No known key found for this signature in database
GPG key ID: 56C7BAAE859B302C
4 changed files with 55 additions and 0 deletions

View file

@ -0,0 +1 @@
../template/Makefile

View file

@ -0,0 +1,32 @@
#include "lib.h"
bool isPalindrome(int x) {
if (x < 0)
return false;
// Find length and calculate divisor
int len = 0;
int div = 1;
int copy = x;
while (copy > 0) {
copy /= 10;
if (len != 0)
div *= 10;
len++;
}
// Compare digits
for (int i=0; i<len/2; i++) {
int a = x / div;
int b = x % 10;
if (a != b)
return false;
// Remove first and last digit
x = x % div;
x /= 10;
div /= 100;
}
return true;
}

View file

@ -0,0 +1,4 @@
#pragma once
#include <stdbool.h>
bool isPalindrome(int x);

View file

@ -0,0 +1,18 @@
#include <stdio.h>
#include "lib.h"
int main() {
int a = 121;
printf("Test 1: %d\n", isPalindrome(a) == 1);
int b = -121;
printf("Test 2: %d\n", isPalindrome(b) == 0);
int c = 1234554321;
printf("Test 3: %d\n", isPalindrome(c) == 1);
int d = 2147483647;
printf("Test 4: %d\n", isPalindrome(d) == 0);
return 0;
}