一个整数“犯二的程度”定义为该数字中包含2的个数与其位数的比值。如果这个数是负数,则程度增加0.5倍;如果还是个偶数,则再增加1倍。例如数字-13142223336
是个11位数,其中有3个2,并且是负数,也是偶数,则它的犯二程度计算为:3/11×1.5×2×100%,约为81.82%。本题就请你计算一个给定整数到底有多二。
输入格式:
输入第一行给出一个不超过50位的整数N
。
输出格式:
在一行中输出N
犯二的程度,保留小数点后两位。
输入样例:
-13142223336
输出样例:
81.82%
注意:该题中的数字范围已经超过长整型,判断2的个数时要通过字符串判断!
代码如下:
import java.text.NumberFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sca = new Scanner(System.in);
String str = sca.next();
double resault = 0;
if (String.valueOf(str.charAt(0)).equals("-")) {
String str2 = str.substring(1);
int number = str2.charAt(str2.length() - 1) - '0';
int num1 = getTwoNumber(str2);
if (number % 2 == 0) {
resault = num1 * 1.0 / str2.length() * 1.5 * 2;
} else {
resault = num1 * 1.0 / str2.length() * 1.5;
}
} else {
int number2 = str.charAt(str.length() - 1) - '0';
int num2 = getTwoNumber(str);
if (number2 % 2 == 0) {
resault = num2 * 1.0 / str.length() * 2;
} else {
resault = num2 * 1.0 / str.length();
}
}
String numberPercent = getPercent(resault, 2);
System.out.println(numberPercent);
}
private static int getTwoNumber(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if ((str.charAt(i) - '0') == 2) {
count++;
}
}
return count;
}
/**
* 获得保留指定位数的百分数
* @param resault 小数
* @param i 保留的位数
* @return 对应的百分数
*/
private static String getPercent(double resault, int i) {
NumberFormat numberFormat = NumberFormat.getPercentInstance();
numberFormat.setMinimumFractionDigits(i);
return numberFormat.format(resault);
}
}
PTA提交结果: