C Programming - String to Integer (atoi)
Another TechMahindra Interview question. The question was to convert a VALID string into its corresponding integer value.Post in your comments!
Solution:
int atoi(char *string)
{
int value=0,sign=1;
if ( !string || !*string ) return 0;
if ( *string == '-' ) {
sign = -1;
string++;
}
while ( *string ) {
if ( (*string >= '0') && (*string <= '9') ) {
value = value * 10 + (*string - '0');
}
else
break;
string++;
}
return sign * value;
}
Labels: C
Posted by - at 9:36 pm | 1 comments read on
C Programming - Reverse Bits in an Integer
It is supposed to be an 32bit integer.Solution:
unsigned int
reverse(register unsigned int x)
{
x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
return((x >> 16) | (x << 16));
}
Labels: C
Posted by - at 7:05 am | 0 comments read on
C Programming - Remove Concequetive Repeting Chars with that Character
What I meant was convert "aaabccddd" to "abcd".Solution:
#include < stdio.h >
#define STRING "aaabccddd"
int replaceCChars(char *string)
{
char *dest=string;
while(*string) {
if ( *string != *(string+1) ) {
*dest++ = *string;
}
string++;
}
*dest = '\0';
}
int main()
{
char a[]=STRING;
printf("Before: %s ",a);
replaceCChars(a);
printf("After: %s\n",a);
}
Labels: C
Posted by - at 6:37 am | 3 comments read on
C Programming - Find Perfect Square Between Two Numbers
TechMahindra Interview Question, this is how I did that.Solution:
#include < stdio.h >
#define START 10
#define STOP 100
int main()
{
int i=0;
while( (i*i) < START ) i++;
while( (i*i) < STOP ) {
printf("%d ",i*i);
i++;
}
}
Labels: C
Posted by - at 6:34 am | 3 comments read on
C Programming - Reverse Words in a String (In-Place)
Another typical interview question!!Here is the solution that I could think off...Post your comments!!!
Solution:
#include < stdio.h >
#define SENT "Hello I am Here"
int reverse(char *string, char delimiter)
{
char *src, *dest,*temp=string;
while( *temp ) {
if (*temp == delimiter) {
temp++;
continue;
}
src=dest=temp;
while ( (*(dest+1) != delimiter) && ( *(dest+1) != '\0' ) ) dest++;
temp=dest+1;
while( dest > src ) {
char temp = *dest;
*dest-- = *src;
*src++=temp;
}
}
}
int main()
{
char name[] = SENT;
printf("Before Call: %s\n",name);
reverse(name,'\0'); /* Reverse Complete Sentence */
reverse(name,' '); /* Reverse Words */
printf("After Call: %s\n",name);
}
Labels: C
Posted by - at 6:29 am | 4 comments read on