Interview Questions

Write a function to print a multiplication table.....

Microsoft Interview Questions and Answers


(Continued from previous question...)

73. Write a function to print a multiplication table.....

Question:
Write a function to print a multiplication table.
Ex.
1 2 3
1 1 2 3
2 2 4 6
3 3 6 9



maybe an answer:

package misc;
public class multiTable {
//print the multiplication table
public static void printMultiTable(int n) {
int[] startPositions = new int[n]; //start positions of the numbers in each row
//compute startPositions according to the last row
startPositions[0] = 0;
for (int i=1;i<n;i++) {
startPositions[i] = startPositions[i-1]+numOfDigit(n*i)+1;
}

//print
StringBuffer sb = new StringBuffer();
for (int i=1;i<=n;i++) { //each row
for (int k=1;k<=n;k++) { //each column
int value = i*k; //the value to print
sb.append(value);
int numOfSpaces = 0;
if (k<n) numOfSpaces = startPositions[k]-startPositions[k-1]-numOfDigit(value);
for (int j=0;j<numOfSpaces;j++) {
sb.append(' ');
}
}
sb.append('\n');
}
System.out.print(sb.toString());
}
//compute the number of digit in n, in which n is larger than 0
public static int numOfDigit(int n) {
int count = 1;
while (n > 0) {
n = n / 10;
count++;
}
return count;
}
public static void main(String[] args) {
printMultiTable(1);
printMultiTable(20);
}
}



maybe an answer2:

#include<stdio.h>
#include<math.h>

int getDigits(double n);

int main()
{

// printf("%d\n", (int)log10(x));

// printf("%d\n",getDigits(1000));
printMultTable(10,10);
}

void printMultTable(int n, int k)
{
int i=1;
int j=1;
int* blocksize = malloc(sizeof(int)*k);
for( i =1;i<=k;i++)
blocksize[i] = getDigits(n*k);

for(i =1;i<=n;i++)
{
for(j=1;j<=k;j++)
{
printSpace(blocksize[k]-getDigits(i*j));
printf("%d",i*j);
printSpace(1);

}
printf("\n");
}


}
void printSpace(int n)
{
int i;
for(i=0;i<n;i++)
printf(" ");

}

int getDigits(double n)
{

return floor(log10(n)) + 1;

}

(Continued on next question...)

Other Interview Questions