[英](Scala) generating a sequence that adds 1 to a n digit number
how do I generate a sequence of size n that would look like this: 如何生成大小为n的序列,如下所示:
n = 3
000
001
002
003
...
010
011
012
...
999
I could use fixed number of for loops for a fixed number of digits but how do i do this with n number of digits in a sequence? 我可以将固定数量的for循环用于固定数量的数字,但是我该如何在序列中使用n个数字呢?
Thank you! 谢谢! ^^ ^^
This will give the output you're looking for but as a Seq
of String
. 这将提供您要查找的输出,但为String
的Seq
。 You can replace 3
with n
to get more or less leading zeros. 您可以将n
替换为3
,以获得更多或更少的前导零。
Range(0,1000).map(n => "%03d".format(n))
scala.collection.immutable.IndexedSeq[String] = Vector(000, 001, 002, 003, 004, 005, 006, 007, 008, 009, 010, 011, ...)
Assuming that: 假如说:
n
specifies the number of digits in the number n
指定数字中的位数 0 to Math.pow(10, n)
范围是从0 to Math.pow(10, n)
A dynamic solution would be: 一个动态的解决方案是:
val n = 3 //Or any number
def upperBound : Int = Math.pow(10, n).toInt
def formatNum(num : Int) : String = s"%0${n}d".format(num)
def range: Range = Range(0, upperBound)
range.map(formatNum)
The main point here being that you can use string interpolation to have variable padding on the numbers using s"..."
, where variables are denoted by $var_name
or ${var_name}
这里的要点是,可以使用字符串插值法使用s"..."
对数字进行变量填充,其中变量用$var_name
或${var_name}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.