繁体   English   中英

返回计数给定数字n中有7位数字

[英]Return the count how many digits are 7 in the given number n

我正在为我的CS151类编写一个称为countSevens(n)的方法。 它返回计数给定数字n中有7位数字。 到目前为止,这就是我所要做的,但是我做错了一些我不知道的错误。

public int countSevens(int n){
    int count = 0;
    String strI = Integer.toString(n);
    for (int i = 0; i < strI.length(); i++){
        if(strI.substring(i).equals("7")){
            count++;
        }
    }
    return count;
}

您可以使用Java流执行此操作

   public int countSevens(int n) {
        return (int) String.valueOf(n).chars().filter(ch -> ch == '7').count();
    }
  • (int)-强制转换为int类型,在这种特殊情况下,将long强制转换为int是安全的,因为我们不会收到会话错误。 在其他情况下,最好使用Math.toIntExact(long)
  • String.valueOf(n)-转换为字符串
  • chars()-返回字符流
  • filter(ch-> ch =='7')-过滤所有等于7的字符
  • count()-返回此流中元素的数量
strI.substring(i)

将字符串的一部分从i字符返回到末尾。

使用strI.charAt(i)代替

根据String.substring(int)的定义:

返回一个字符串,该字符串是该字符串的子字符串。 子字符串以指定索引处的字符开头,并延伸到该字符串的末尾。

因此,这只会算出您号码中7的最后一个实例,并且仅是数字中的最后一位。

相反,请尝试以下操作:

if(strI.substring(i, i+1).equals("7"))

或者,由于您要处理整数,因此可以避免完全使用字符串。 n % 10将使您获得最后一位数字,而n /= 10将使整个数字右移一位数字。 这应该足以让您开始不使用String进行此操作。

要计算整数中的7s:

int counter = 0;
int number = 237123;
String str_number = String.valueOf(number);
for(char c : str_number.toCharArray()){
    if(c == '7'){
        counter++;
    }
}

您可以使用简单的算法:

public static int countSevens(int i) {
    int count = 0;
    for (i = i < 0 ? -i : i; i != 0; count += i % 10 == 7 ? 1 : 0, i /= 10);
    return count;
}

但是谁能读懂这个? 数量不多,因此这里是使用相同逻辑的更干净的解决方案:

public static int countSevens(int i) {
    int count = 0;

    // ignore negative numbers
    i = Math.abs(i);

    while(i != 0) {
        // if last digit is a 7
        if(i % 10 == 7) {
            // then increase the counter
            count++;
        }

        // remove the last digit
        i /= 10;

    }
    return count;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM