Question d'entretien d'embauche Facebook: Given a number of size <= 999... | Glassdoor.fr

Question d'entretien d'embauche

Entretien de Software Engineer New Grad New York, NY (États-Unis)

Given a number of size <= 999 billion, return its String

  representation (for 123, return "One Hundred Twenty Three," not "123").
Répondre

Réponse de l'entretien

2 réponses

1

// Can retrieve the String mapping from its numerical index
public static final String[] LESS_THAN_20 = new String[]{"", "One", ... , "Nineteen"};
public static final String[] LESS_THAN_100 = new String[]{"", "Ten", "Twenty", ... , "Ninety"};
public static final String[] OTHER = new String[]{"", "Thousand", "Million", "Billion"};
public String integerToString(int num) {
    if (num == 0) return "Zero";
    String res = "";
    int index = 0; // Access word representations for num values &gt;= 1000
    while (num != 0) {
        if (num % 1000 != 0) // This was the edge case I was stuck on. Say num is a value of &gt;= 1 million such that there are no non-zero digits for the thousands place values (e.g. 1,000,001), if this conditional was not checked, the result would be "One Million Thousand One" instead of "One Million One"
            res = generate(num % 1000) + OTHER[index] + " " + res;
        num /= 1000; // Move to the next range of digits
        index++;
}
return res;

private String generate(int num) {
    if (num &lt; 20) return LESS_THAN_20[num] + " ";
    else if (num &lt; 100) return LESS_THAN_100[num / 10] + " " + generate(num %10);
    else return LESS_THAN_TWENTY[num / 100] + " Hundred " + generate(num % 100);
}

Candidat à l'entretien, le 5 août 2017

Un ou plusieurs commentaires ont été supprimés.
Veuillez consulter lesRègles de la communauté ou les Conditions d'utilisation pour plus d'informations.

Ajouter des réponses ou des commentaires

Pour commenter ceci, se connecter ou s'inscrire