我要寻找一个方法,去除所有的9从整数:从另一个数字中删除所有9的Java方法?
public int noNine(int i){
int res = 0;
return res;
}
例子:
noNine(0)->0
noNine(1991)->11
noNine(99)->0
noNine(19293949)->1234
等。
不允许使用字符串,也不允许使用外部方法。
你能帮我吗?
谢谢!
埃迪德州
我要寻找一个方法,去除所有的9从整数:从另一个数字中删除所有9的Java方法?
public int noNine(int i){
int res = 0;
return res;
}
例子:
noNine(0)->0
noNine(1991)->11
noNine(99)->0
noNine(19293949)->1234
等。
不允许使用字符串,也不允许使用外部方法。
你能帮我吗?
谢谢!
埃迪德州
你可以做这样的:
public int removeNines(int n) {
int returnValue = 0, multiplier = 1;
while (n > 0) {
if (n%10 != 9) {
returnValue += (n%10) * multiplier;
multiplier *= 10;
}
n /= 10;
}
return returnValue;
}
这个循环遍历所有的数字,如果不是9它把它添加到输出。测试here和作品
int removeNine(int n)
{
int result = 0;
int mul = 1;
while(n > 0)
{
//check if current digit is 9. if 9 then do nothing
if(n % 10 == 9)
{
n = n/10;
continue;
}
else
{
//if not 9 then add this to result after multiplying by current mul
result += mul * (n % 10);
//update mul so that the next digit is added according to power of 10
mul = mul * 10;
}
n = n/10;
}
return result;
}
'如果(n%10 == 9)继续;'不能正确。如果条件成立,它将陷入无限循环。 –
@PaulBoddington有n/10后,所以它不会卡住在同一个数字 – Monkeygrinder
@PaulBoddington你是对的。我修好了它。 – ritratt
这里是我的版本写在一个稍微不同的方式ritratt以防万一你不理解他的版本:
public int noNines(int num) {
int multiplier = 0;
int result = 0;
while (num > 0) {
int digit = num % 10;
System.out.println("digit=" + digit);
if (digit == 9) {
//ignore
} else {
System.out.println("Adding " + (digit * (int)Math.pow(10, multiplier)));
result += digit * (int)Math.pow(10, multiplier);
multiplier++;
}
num = num/10;
}
return result;
}
我离开控制台输出,所以你可以看到方法在行动。
你可以解决多种方式
我要阐述一下第二种方法:
使用这种技术,您可以使用整数或字符串来解决问题。如你所说,我将使用intergers它是一个必需的方面:
返回终值
public int noNine(int i){
if(i < 10){
if(i == 9)
return 0;
else
return i;
}
int lastDigit = i % 10;
if(lastDigit == 9)
return noNine(i/10);
else
return noNine(i/10)*10+lastDigit;
}
这里的关键外卖是:n % 10 = last digit of n
和n/10 = all previous digits of n
。这是由于Java中的整数除法造成的!
你将不得不最终使用一个字符串...它会看起来像这样....返回Integer.parseInt(Integer.toString(i).replaceAll(“9”,“ “));' – 3kings
你确定你不能转换为一个字符串只是为了删除9,然后转换回int? –
我不允许使用任何字符串。 – TexasEddie