【问题标题】:need to write this code by not using 0?0 form? [closed]需要不使用 0?0 形式来编写此代码吗? [关闭]
【发布时间】:2014-05-03 07:16:07
【问题描述】:
public static void main(String args[]){ 
  System.out.println(countDigitX(8888,8)); 
}

public static intcountDigitX(int n, int x) { 
  return n==0?0:(n%10==x?1:0)+countDigitX(n/10,x); 
}
}//end of class

【问题讨论】:

  • 您能否详细介绍一下您的问题?
  • 那么您了解条件运算符的作用吗?如果是这样,重写它应该相当容易。如果没有,请参阅stackoverflow.com/questions/798545/…
  • 是的,这里的问题是:编写一个递归 Java 方法 countDigitx,它接受两个整数作为输入(一个数字 n 和数字 x)并返回数字 x 在数字 n 中出现的次数:例如如果 n=23242 且 x=2,则该方法应返回 3,即 n 中找到的数字 2 的倍数。
  • 请把问题放到实际问题中,不要埋在cmets中。
  • @ScottMcGready:这不是真正的问题,这只是家庭作业。问题是如何摆脱三元语法。

标签: java


【解决方案1】:
public static intcountDigitX(int n, int x) {
    int result;
    if( n == 0 ) {
        result = 0;
    } else {
        if( n % 10 == x ) {
            result = 1;
        } else {
            result = 0;
        }
        result += countDigitX(n/10, x);
    }
    return result;
}

【讨论】:

  • 非常感谢我的朋友
【解决方案2】:

你可以改写如下:

public static int intcountDigitX(int n, int x) {

        if (n == 0) {
            return 0;
        } else if (n % 10 == x) {
            return 1 + countDigitX(n / 10, x);
        }

        return 0 + countDigitX(n / 10, x);
    }

【讨论】:

    【解决方案3】:

    编辑:

             if(n==0) {
             return 0
             }else if(n%10==x){
             return 1+countDigitX(n/10,x);
             }else{
             return 0+countDigitX(n/10,x);
             }
    

    【讨论】:

    • 这似乎不会在 n==0 时返回 0,而原始代码会这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多