给定一个整数数组,返回数组中 9 的个数

基本上这个问题的目的是计算数字 9 在数组中输入的次数,例如 arrayCountNines([1, 9, 9, 3, 9]) = 3


我尝试过进行数字流,例如使用 .collect 但似乎不起作用。还尝试过 HashMap


    public class NewClass4 {

   public int arrayCountNines(int[] nums) {

      HashMap < Character, Integer > map = new HashMap<>();

      for (int i =0; i<nums.length; i++) {

          char[] charr = String.valueOf(nums[i]).toCharArray(); 

          for(int j = 0; j<charr.length; j++) {

              if(map.containsKey(charr[j])) {

                  map.put(charr[j], map.get(charr[j])+1); 

              }

              else {

                  map.put(charr[j], 1);

              }

          }

      }

      return 1; 


}



    }

]1


它不返回 9 在数组中出现的次数


慕仙森
浏览 133回答 4
4回答

ibeautiful

尝试一下:&nbsp; &nbsp;public int arrayCountNines(int[] nums) {&nbsp; &nbsp; &nbsp; int count=0;&nbsp; &nbsp; &nbsp; for (int i =0; i<nums.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int v = nums[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (v==9) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;count++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; return count;&nbsp;&nbsp; &nbsp;}

慕的地8271018

public&nbsp;int&nbsp;arrayCountNines(int[]&nbsp;nums)&nbsp;{ &nbsp;&nbsp;&nbsp;return&nbsp;(int)&nbsp;Arrays.stream(nums).filter(value&nbsp;->&nbsp;value&nbsp;==&nbsp;9).count(); }

慕桂英4014372

尝试这个简单的方法:public int arrayCountNines(int[] nums) {&nbsp; &nbsp; int result = 0;&nbsp; &nbsp; for(int i = 0; i < nums.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; if(nums[i] == 9){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return result;}

POPMUISE

难道不能使用 for 循环遍历数组,然后在该项等于 9 时将其添加到计数器中吗?...int nineCounter = 0;for(int i=0; i<array.length ; i++){&nbsp; if(array[i] == 9){&nbsp; &nbsp; nineCounter++;&nbsp; }}return nineCounter;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java