【问题标题】:Find number of occurrences of digits from 1 to N without using loop在不使用循环的情况下查找从 1 到 N 的数字出现次数
【发布时间】:2015-02-09 16:21:10
【问题描述】:

例如n=11表示,那么地图应该有0-1, 1-4, 2-1, 3-1, 4-1, 5-1, 6-1, 7-1 , 8-1, 9-1

 public void countDigits(int n, Map map) {
          while (n != 0) {
            int d = n%10;
            n /= 10;
            map.put(d,map.get(d)++);
          }
          return result;
        }

上述方法除外。 我想得到从 1 到 N 的所有数字。

【问题讨论】:

  • 我不认为您的循环正在做您希望它做的事情。您是从其他从 1 迭代到 n 的循环中调用它吗?
  • 您的问题没有明确说明。请澄清您的问题。
  • 您的预期输出背后的逻辑是什么?请解释一下。
  • 递归有一个简单的方法。将 f(10a+b) 写为 f(a)、b 和 countDigits(a) 的函数。
  • 你有什么问题?

标签: java math number-theory induction


【解决方案1】:

您的代码根本无法编译。尝试用

替换map.put(d,map.get(d)++);
Integer tmp = (Integer)map.get(d);
if(tmp == null) tmp = 0;
tmp++;
map.put(d,tmp);

【讨论】:

  • 这不是一个确切的代码。只是一个不需要的骨架。
猜你喜欢
  • 2013-06-25
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 2017-02-22
  • 2019-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多