红宝石般的问题:使此功能更短的(动作3)红宝石、此功能、更短、动作

2023-09-08 11:10:17 作者:男sんêηぷ尠гοǔ

我刚刚写了这个令人难以置信的详细code打开像2号到02 可以让这个功能更短,请(maintaning的功能)?

I just wrote this incredibly verbose code to turn numbers like 2 into 02. Can you make this function shorter, please (maintaning the functionality)?

	public static function format(n:int, minimumLength:int):String {
		var retVal:String = n.toString();
		var stillNeed:int = minimumLength - retVal.length;
		for (var i:int = 0; i < stillNeed; i++) {
			retVal = "0" + retVal;
		}
		return retVal;
	}

请使用类型变量。加分(好氛围点,没有那么点),如果有已经是一个内置的功能,我不知道。

Please use types for variables. Extra points (good-vibe points, not SO points) if there's already a built-in function that I don't know about.

如果有人想发表一些极短的相当于在其他一些语言,这将是一种乐趣。

If anybody wants to post some extremely short equivalent in some other language, that would be fun too.

推荐答案

这不会是最快的实现(它做了一些不必要的复制,并具有循环),但它的是不错,可读

This wouldn't be the fastest implementation (it does some unnecessary copying and has a loop), but it is nice and readable:

public static function pad(num:int, minLength:uint):String {
    var str:String = num.toString();
    while (str.length < minLength) str = "0" + str;
    return str;
}