1. Explain what the code does.
2. Write test cases and check for any bugs.
3. Explain the purpose of the StringBuilder class in this code.
You are given a C# implementation that converts an integer into its English words representation, such as turning 123 into "one hundred twenty three". Review the code, describe its behavior, identify edge cases or bugs, and explain why StringBuilder is used.
using System;
using System.Text;
namespace Solution
{
public class Solution
{public static void Main(string[] args)
{
// you can write to stdout for debugging purposes, e.g.
Console.WriteLine("This is a debug message");
}
public static string Foo(int number)
{StringBuilder result = new StringBuilder();
string[] multiplier = { ""," thousand "," million "," billion "};
int multiplierCounter = 0;
bool isNegative = number < 0;
if (number == 0)
return "zero";
if (isNegative)
number = Math.Abs(number);
while (number > 0)
{if (number % 1000 > 0)
{result.Insert(0, multiplier[multiplierCounter++]);
result.Insert(0, ConvertThreeDigits(number % 1000));
}
number /= 1000;
}
while (result.Length > 0 && char.IsWhiteSpace(result[result.Length - 1]))
result.Length = result.Length - 1;
if (isNegative)
{result.Insert(0, "-");
result.Append(' ');
}
return result.ToString();}
private static string ConvertThreeDigits(int number)
{StringBuilder result = new StringBuilder();
string[] englishTextNumbers = { "","one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"};
string[] englishTextTens = { "","", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
}
这道题本质上是在考察一个“整数转英文单词”函数的实现思路与代码审查能力。核心做法通常是把数字按 1000 分组,分别处理个、thousand、million、billion 等层级,再用一个辅助函数把 0~999 转成英文描述,最后用 StringBuilder 进行高效拼接。面试时除了讲清楚整体流程,还要重点检查边界条件,例如 0、负数、整千整百万的空格处理,以及可能存在的下标越界或负数取绝对值溢出问题。