作为一个单一的值返回多个整数
嘿,我正在研究一种方法,从两个传递的整数中选取最小的数字,然后返回一个由最小值组成的整数地点。例如,如果int a = 4321和int b = 1957,那么该方法将返回1321.这是我的代码到目前为止,我想我得到了一切,但我无法找到如何正确返回新值作为整数。作为一个单一的值返回多个整数
public static int biggestLoser(int a, int b){
int first;
int second;
int third;
int fourth;
if(a>9999 || a<1000 || b>9999 || b<1000){
if(a>b)
return b;
else
return a;
}
else{
if(a%10 < b%10)
first=a%10;
else
first=b%10;
if(a/1000<b/1000)
fourth=a/1000;
else
fourth=b/1000;
if(a/100%10<b/100%10)
second=a/100%10;
else
second=b/100%10;
if(a/10%10<b/10%10)
third=a/10%10;
else
third=b/10%10;
//int total=fourth,third,second,first;?????
//return total;
}
}
首先有一个小错误。您必须交换代码second
和third
。
if(a/100%10<b/100%10)
third=a/100%10;
else
third=b/100%10;
if(a/10%10<b/10%10)
second=a/10%10;
else
second=b/10%10;
修复它之后简单地说:
int total = first + 10 * second + 100 * third + 1000 * fourth;
return total;
就是这样。
S%* @我没有注意到谢天谢地! – nebularis 2014-09-23 02:16:06
您可以先形成一个字符串,并做一个Integer.parseInt()
或做一些数学一样int total = (first*1)+(second*10)+(third*100)+(fourth*1000);
。
谢谢你做到了! – nebularis 2014-09-23 02:12:29
这将是更好地执行这样的事情:
的所有代码int returnValue = 0;
for(int digit = 0; digit < 4; digit++) {
int aDigit = (a/Math.pow(10, digit)) % 10; // Gets the digit
int bDigit = (b/Math.pow(10, digit)) % 10;
int max = (a > b)? a : b; // Calculates de maximum digit
returnValue += max * Math.pow(10, digit); //Adds the new digit to the return value
}
return returnValue;
Math.pow效率非常低,但他只需要乘以整数。 – 2014-09-23 02:10:33
谢谢,但它太复杂了! – nebularis 2014-09-23 02:12:48
int i=1000,z=0;
do{
int x = a/i;
a=a%i;
int y = b/i;
b=b%i;
if(x<y)
z+=x*i;
else z+=y*i;
i=i/10;
}while(i>0);
return z;
//this is just logic, works for 4 digit numbers
只是将值作为int数组返回。我已经重构你的方法来做到这一点
public static int[] biggestLoser(int a, int b){
int first;
int second;
int third;
int fourth;
int [] values;
if(a>9999 || a<1000 || b>9999 || b<1000){
if(a>b)
return b;
else
return a;
}
values = new int[4];
else{
if(a%10 < b%10)
first=a%10;
else
first=b%10;
if(a/1000<b/1000)
fourth=a/1000;
else
fourth=b/1000;
if(a/100%10<b/100%10)
second=a/100%10;
else
second=b/100%10;
if(a/10%10<b/10%10)
third=a/10%10;
else
third=b/10%10;
//int total=fourth,third,second,first;?????
values[0] = first;
values[1] = second;
values[2] = third;
values[3] = fourth;
return value;
}
}
在你的主要方法,你现在可以通过获取数组中的每个元素的循环
for(int x : values){
System.out.print(x);
}
考虑按10乘以增加,就像你在纸上做的一样。不要让它变得更复杂,那就是 - 基本的3级算术。 – 2014-09-23 02:07:54