Problem 9: palindrome number
This commit is contained in:
parent
b63e4594d9
commit
3b71bbbca8
4 changed files with 55 additions and 0 deletions
1
problems/9-palindrome-number/Makefile
Symbolic link
1
problems/9-palindrome-number/Makefile
Symbolic link
|
@ -0,0 +1 @@
|
|||
../template/Makefile
|
32
problems/9-palindrome-number/lib.c
Normal file
32
problems/9-palindrome-number/lib.c
Normal 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;
|
||||
}
|
4
problems/9-palindrome-number/lib.h
Normal file
4
problems/9-palindrome-number/lib.h
Normal file
|
@ -0,0 +1,4 @@
|
|||
#pragma once
|
||||
#include <stdbool.h>
|
||||
|
||||
bool isPalindrome(int x);
|
18
problems/9-palindrome-number/main.c
Normal file
18
problems/9-palindrome-number/main.c
Normal 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;
|
||||
}
|
Loading…
Reference in a new issue