【发布时间】:2014-12-31 14:15:58
【问题描述】:
好的,所以我有一个练习要做,我需要找到一个数字中的最高位和最低位并将它们加在一起。所以我有一个数字 n,它是 5368,代码需要找到最高位 (8) 和最低的 (3) 数字并将它们加在一起 (11)。我该怎么做?我尝试过这样的事情:
public class Class {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n1 = 5;
int n2 = 3;
int n3 = 6;
int n4 = 8;
int max = Math.max(n2 ,n4);
int min = Math.min(n2, n4);
int sum = max + min;
System.out.println(sum);
}
}
哪种方法可行,但我在这里有一个 4 位数字,并且使用 Math.max/min 我只能使用 2 个参数。我该怎么做?提前致谢。
【问题讨论】:
-
一种解决方案:使用
String.valueOf(int)将您的号码转换为String,获取其char[],对其进行排序,获取第一个和最后一个索引。要提取每个字符的值,只需使用c - '0'。就是这样!
标签: java numbers digit highest