2015-11-04 106 views
2

我要寻找一个方法,去除所有的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 

等。

不允许使用字符串,也不允许使用外部方法。

你能帮我吗?

谢谢!

埃迪德州

+1

你将不得不最终使用一个字符串...它会看起来像这样....返回Integer.parseInt(Integer.toString(i).replaceAll(“9”,“ “));' – 3kings

+1

你确定你不能转换为一个字符串只是为了删除9,然后转换回int? –

+0

我不允许使用任何字符串。 – TexasEddie

回答

0

你可以做这样的:

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和作品

6
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; 
} 
+0

'如果(n%10 == 9)继续;'不能正确。如果条件成立,它将陷入无限循环。 –

+0

@PaulBoddington有n/10后,所以它不会卡住在同一个数字 – Monkeygrinder

+1

@PaulBoddington你是对的。我修好了它。 – ritratt

0

这里是我的版本写在一个稍微不同的方式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; 
    } 

我离开控制台输出,所以你可以看到方法在行动。

3

你可以解决多种方式

  1. 这个问题通过每个字符
  2. 使用一个for循环来循环使用递归

我要阐述一下第二种方法:

使用这种技术,您可以使用整数或字符串来解决问题。如你所说,我将使用intergers它是一个必需的方面:

  1. 使用%10
  2. 删除它,如果它是一个9
  3. 递归查询每个数字(获取最后一位*记住!有一个基本情况)
  4. 返回终值

    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 nn/10 = all previous digits of n。这是由于Java中的整数除法造成的!

相关问题