Sunday, September 27, 2009

Modify io_display function

Challenge: Modify io_display function to the shortest code possible.

void io_display(const char *str, int row, int col, int len){
io_move(row, col);
(len <= 0) ? io_putstr(str) : for(int i=0; i < len; i++)
io_putch(i < strlen(str) ? str[i] : ' ');
}

Thursday, September 17, 2009

new solution of GetInt(char *strint, int val)

There are some improvements in Cong Wang's solution of the first challenge.

1. it does not handle negative integer
2. it does not handle integer zero

Cong Wang's solution
==============================================
void GetInt(char *strint, int val){

char rev[100];

int length=0;

while (val > 0)
{
int a = val % 10;
rev[length++] = a | '0';
val /= 10;
}
rev[length]='\0';


length--;
int rev = 0;
while (length >= 0)
{
strint[rev++] = rev[length--];
}

strint[rev] = '\0';
}
==============================================


my new solution
==============================================


void GetInt(char *strint, int val) {
int len = 0;
bool negative = false;

if(val < 0) { // if negative
val = -val;
negative = true;
} else if (val == 0) { // if 0
strint[len++] = '0';
}

while (val > 0) {
strint[len++] = (val % 10) + '0';
val /= 10;
}

if(negative) {
strint[len++] = '-';
}

// reverse this string
for(int i=0; i < len /2; i++) {
char a = strint[i];
strint[i] = strint[len-1-i];
strint[len-1-i] = a;
}

strint[len] = '\0';
}

Wednesday, September 16, 2009