我写了一个类,通过将两位数相加来找到一个整数的总和。例如,0, 5, 12, 213, 999 and 1111
的数字总数是
分别为0,5,3,6,27和4。我需要写一个方法:
public static double digitTotalFrequency(int max, int digitTotal)
此方法应该return
具有0,1 ... max范围内所有数字的给定digitTotal
的数字的比例。例如,digitTotalFrequency(9, 3)
为0.1
,因为前10个数字中只有一个数字的总数为3.此外,digitTotalFrequency(99,3)
为0.04
(因为前100个数字中的数字)只有数字3,12,21和30的数字总数为30)。我很难做到这一点,请帮助,谢谢。
public static double digitTotalFrequency(int max, int digitTotal){
int number = max;
while (number>0) {
digitTotal = digitTotal + (number%10);
number = number/10;
}
return digitTotal/max;
}
答案 0 :(得分:0)
您需要将任务分为两部分
这被称为动态编程或记忆。
尝试稍微考虑一下。如果你挣扎,我可以开始使用一些代码
编辑:程序代码
尝试阅读本文,看看到底发生了什么
public class Jnk {
public static void main(String[] args) {
System.out.println(digitTotalFrequency(99,3));
}
public static double digitTotalFrequency(int max, int digitTotal){
HashMap<String,Integer> counts = new HashMap<String,Integer>();
counts.put("0", 0);
counts.put("1", 1);
counts.put("2", 2);
counts.put("3", 3);
counts.put("4", 4);
counts.put("5", 5);
counts.put("6", 6);
counts.put("7", 7);
counts.put("8", 8);
counts.put("9", 9);
int [] runs = new int[1];
if(max<=10)
return (double)digitTotal/max;
else
getTotal(0,max,counts,runs,digitTotal);
return (double)runs[0]/max;
}
private static void getTotal(int currentNumber, int max, HashMap<String, Integer> counts,int [] runs, int target) {
if(currentNumber==max)
return;
String key = getKey(currentNumber);
if(counts.containsKey(key))
{
int total = counts.get(key);
if (total==target)
{
System.out.println("Found "+currentNumber);
runs[0] += 1;
}
getTotal(currentNumber+1,max,counts,runs,target);
}
else
{
int total = getDigitCount(currentNumber);
counts.put(key, total);
if (total==target)
{
System.out.println("Found "+currentNumber);
runs[0] += 1;
}
getTotal(currentNumber+1,max,counts,runs,target);
}
}
private static Integer getDigitCount(int currentNumber) {
int digitTotal = 0;
while (currentNumber>0) {
digitTotal = digitTotal + (currentNumber%10);
currentNumber = currentNumber/10;
}
return digitTotal;
}
private static String getKey(int min) {
String number = String.valueOf(min);
char[] numberArray = number.toCharArray();
Arrays.sort(numberArray);
String key = String.valueOf(numberArray);
return key;
}
}