如何将整数转换为数字列表[请阅读第页中的详细信息]



我最好用一个例子来表达这一点,我正在尝试编写一个程序,比如我有一个这样的函数:

static List<Integer> int2List(int l, int base)

输入和输出应该是

l=0, base=3, return {1}
l=1, base=3, return {2}
l=2, base=3, return {3}
l=3, base=3, return {1,1}
l=4, base=3, return {1,2}
l=5, base=3, return {1,3}
l=6, base=3, return {2,1}
l=7, base=3, return {2,2}
l=8, base=3, return {2,3}
l=9, base=3, return {3,1}
l=10, base=3, return {3,2}
l=11, base=3, return {3,3}
l=12, base=3, return {1,1,1}
l=13, base=3, return {1,1,2}
l=14, base=3, return {1,1,3}

这很像递归mod,但有一些条件我无法理解。

谢谢

感谢您的所有评论,我已经更新了问题内容和方法的签名,我想显示列表的内容,但我忘记在元素之间添加逗号。

这是我的代码,它还不正确,但我认为你可以从中得到一些理解。它也很像Long.toString(int I,int radix),区别在于首先我需要添加那些前导零,其次我需要从列表中的每个元素中做一个"+1",但这样做也不能让我正确。。。

static List<Integer> int2List(int l, int base) {
//        String s = Long.toString(l,base);
List<Integer> list = new ArrayList<Integer>();
int k = l % base;
int j = l / base;
int m = 0;
list.add((int) (k + 1));
while (j > base) {
k = j % base;
list.add((int) (k));
if (j == base)
break;
j = j / base;
}
if (j == base) {
list.add((int) (j));
} else {
if (j > 0) {
list.add((int) (j));
}
}
Collections.reverse(list);
return list;
}

我知道我在第一个版本中犯的错误,我现在纠正了我的错误,并将问题更新为更具体的问题,你能删除"不值得阅读"吗?我真的很感激。。

===================

嗯,该方法应该在循环中使用,这样它将输出由范围[1,base]中的数字组成的所有可能的序列,并且l可以被视为索引。

这个怎么样?

static List<Integer> int2List(int l, int base)
{
List<Integer> list = new ArrayList<Integer>();
int n;
l++;
while(l > 0)
{
n = (l-1) % base;
list.add(0, (int) n+1);
l = (l-n)/base; 
}
return list;
}

我认为您的方法签名是错误的。该函数似乎将数值转换为其基本表示

这意味着,返回值必须包含String。

您使用列表<…>的原因我不清楚。

最新更新