Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[C] challenge 13(Unreviewed) #423

Merged
merged 3 commits into from
Jan 18, 2017
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
O(1) method
Earlier method used Dynamic Arrays to check for palindrome which took O(n) space. This method just reverses the input number and checks if it is the same as the original.
  • Loading branch information
karanchawla committed Jan 18, 2017
commit 6f72105931e8b55b45aef2c4e70aa9e3e0af31b7
91 changes: 17 additions & 74 deletions challenge_13/c/karanchawla/challenge_13.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,81 +4,17 @@
#include <stdio.h>
#include <stdlib.h>

// Dynamic Array Definition
//////////////////////////////////////////////////////////////////////////////////
typedef struct {
int *array;
size_t used;
size_t size;
} Array;

void initArray(Array *a, size_t initialSize)
{
a->array = (int *)malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}

void insertArray(Array *a, int element)
int reverse(int x)
{
// a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
// Therefore a->used can go up to a->size
if (a->used == a->size)
int ans = 0;
while(x != 0)
{
a->size *= 2;
a->array = (int *)realloc(a->array, a->size * sizeof(int));
ans = ans * 10;
ans = ans + x%10;
x = x/10;
}
a->array[a->used++] = element;
}

void freeArray(Array *a)
{
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
/*
Array a;
int i;
initArray(&a, 5); // initially 5 elements
for (i = 0; i < 100; i++)
insertArray(&a, i); // automatically resizes as necessary
printf("%d\n", a.array[9]); // print 10th element
printf("%d\n", a.used); // print number of elements
freeArray(&a);
*/
///////////////////////////////////////////////////////////////////////////////////

void isPalindrome(int num)
{
Array a;
initArray(&a,1);
while(num)
{
insertArray(&a, num%10);
num /= 10;
}

int size = a.used;

int flag = 1;
for(int i=0;i<size/2;i++)
{
if(a.array[i]==a.array[size-i-1])
{
flag = 1;
}
else
{
flag = 0;
break;
}
}

if(flag) printf("True\n");
else printf("False\n");

freeArray(&a);

return ans;
}


Expand All @@ -87,7 +23,14 @@ int main(void)
{
int num = 1234554321;

isPalindrome(num);
if(reverse(num)==num)
{
printf("True");
}
else
{
printf("False");
}

return 0;
}
}