Microsoft Interview Question
Country: India
I think this is not correct. For each char in string you need to have two bytes in array. So "j=2*len-1" is not correct. It should be "j=3*len-1". Please let me know if I am wrong.
void print_ascii(char str[] ){
int len = strlen(str);
int last_index = len - 1;
int i =0,j,count = 0;
int val;
while(count < len){
for ( j = last_index ; j >= i ; j -- )
str[j+1] = str[j];
val = str[i];
str[i] = '0'+(val/10);
str[i+1] = '0'+(val%10);
last_index++;
i = i + 2;
count++;
}
str[last_index + 1 ] = '\0';
printf("\n ans str = %s",str);
}
void str_to_ascii(char *a)
{
if(!a)
return;
else
{
int orig_len=strlen(a);
int new_len=orig_len*2;
int i,j,value;
for(i=orig_len-1, j=new_len-1; i>=0; i--, j--)
{
value=a[i];
a[j]=(int)'0'+(value%10);
j--;
value=value/10;
a[j]=(int)'0' + value;
}
a[new_len]='\0';
}
This is assuming that the original string(array) has enough spaces at its end to accomodate the double digits of ascii values and also that the string is in uppercase characters only.
Since we're working with "in-place", I'm assuming we're going to pass in something that's more edit-friendly (I'm using Java). So I'm using StringBuilder:
public class ToAscii
{
public static void toAscii(StringBuilder sb)
{
int length = sb.length();
int numberOffset = 0;
for(int i = 0; i < length; i++)
{
String numberString = new String("" + (int)sb.charAt(numberOffset));
sb.insert(numberOffset, numberString);
numberOffset += numberString.length();
sb.deleteCharAt(numberOffset);
}
System.out.println(sb.toString());
}
}
//this is working fine
void print_ascii(char str[] ){
int len = strlen(str);
str=(char *)realloc(str,2*len*(sizeof(char)));
int i=0;
int j;
str[2*len]='\0';
for(j=(2*len)-1;j>=1;){
i=(int)j/2;
str[j] = (char)(48+(str[i]%10));
str[j-1] = (char)(48+(str[i]/10));
j=j-2;
}
printf("%s\n",str);
}
- Dheeraj Sharma March 15, 2012