+ 2
Could anyone tell me easy approach to make code shorter for No Numerals
I do stick more code than anyone I think I wanna know on how to code shorter and better that work the same way a longer one do for example: code coach problem No Numerals how to tackle it easier way
5 Antworten
+ 3
Vishal shared most of his code.
Response:
The first thing I recommend is to remove your goto statement. You could print your number in a separate function called "num" instead. Replacing a goto statement and label with a function won't shorten the code but it should make it more understandable to the average programmer.
The next is I'd replace the switch statement for printing those digits as words with an array like I shared in an earlier comment. This would shorten the code a lot. See my printWord function from a previous comment to see how short it is.
arr[i] >= 48 && arr[i]<=57
could be replaced with arr[i] >= '0' && arr[i]<='9'
I find the char literals to be more readable and understandable than their corresponding integers. Interpreting 48 as a human requires me to remember that 48 == '0'. If you include ctype.h, you could use isdigit(arr[i]).
Another improvement would be with indentation. The number of open { or nested code blocks should correspond with how deep indentation is.
+ 1
How short is your c solution?
A switch statement or lengthy if-else is tempting for printing the words but I used an array to shorten that part.
I solved it in c with this:
#include <stdio.h>
const char* words[11] = {
"zero","one","two","three","four","five","six","seven","eight", "nine", "ten"
};
void printWord(int i)
{
printf(words[i]);
}
int main() {
char c;
while ((c = getchar()) != EOF)
{
if (c >= '0' && c <= '9')
{
if (c == '1')
{
c = getchar();
if (c == '0')
printWord(10);
else
{
printWord(1);
printf("%c", c);
}
}
else
printWord((int)(c - '0'));
}
else
printf("%c", c);
}
return 0;
}
0
#include <stdio.h>
#include <string.h>
int main() {
char arr[100];
fgets(arr, sizeof(arr), stdin);
int s= strlen(arr);
for(int i=0; i< s; i++){
if(arr[i] == '1'){
if(arr[i+1] == '0'){
printf ("ten");
i+=2;
}
}
if(arr[i] >= 48 && arr[i]<=57){
goto num;
}
printf ("%c", arr[i]);
num:
switch (arr[i])
{
case '0':
printf ("zero");
break;
case '1':
printf ("one");
break;
case '2':
printf ("two");
break;
case '3':
printf ("three");
break;
case '4':
printf ("four");
break;
case '5':
printf ("five");
break;
case '6':
printf ("six");
break;
.........case '9':
....
....
0
Josh Greig
Thank you sir for helping me out
0
G'day Vishal how have you developed with making your code more terse (less verbose)?
I like your use of getchar instead of scanf
I love your use of the ASCii numbers instead of '0' to '9'
This is my solution (before seeing how everyone has done it!)
https://code.sololearn.com/cBd8Wzeidx4u/?ref=app