Friday, March 21, 2014

Recursion to the rescue

Q:
Given only putchar (no sprintf, itoa, etc.) write a routine putlong that prints out an unsigned long in decimal.
A:

Solution 1: iteratively  divide 
Step 1:  find the max 10^k , that it can be divided
Step 2:  print the division,    recall the mod,


    static void printLong(long a) {
        if (a < 0) {
            return;
        }
        if (a == 0) {
            printChar('0');
        } else {
            int tens = 1;
            while (a / tens >= 10) {
                tens *= 10;
            }
            while (tens > 0) {
                int b = (int) (a / tens);
                printChar((char) (b + '0'));
                a = a % tens;
                tens /= 10;
            }

        }
    }

    static void printChar(char ch) {
        System.out.print(ch);
    }



Solution 2:  recursive call its  1/ 10


    static void printLong(long a) {
        // assume that input is unsigned integer
        if (a < 10) {
            printChar((char) (a + '0'));
        } else {
            printLong(a / 10);
            printChar((char) (a % 10 + '0'));// print the last char
        }
    }

    static void printChar(char ch) {
        System.out.print(ch);
    }


-----------------------------------------Problem 2 ----------------------------------
Q:
Print a string in reverse order.

A:
void printReverse(const char *str) {
  if (!*str)
    return;
  printReverse(str + 1);
  putchar(*str);
}


No comments:

Post a Comment