L1-017 到底有多二
一个整数“犯二的程度”定义为该数字中包含 2 的个数与其位数的比值。如果这个数是负数,则程度增加 0.5 倍;如果还是个偶数,则再增加 1 倍。例如数字-13142223336
是个 11 位数,其中有 3 个 2,并且是负数,也是偶数,则它的犯二程度计算为:3/11×1.5×2×100%,约为 81.82%。本题就请你计算一个给定整数到底有多二。
输入格式:
输入第一行给出一个不超过 50 位的整数N
。
输出格式:
在一行中输出N
犯二的程度,保留小数点后两位。
输入样例:
tex
-13142223336
-13142223336
输出样例:
tex
81.82%
81.82%
Solution:
java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
char[] chars = in.readLine().toCharArray();
double ans = 1, two = 0;
int length = chars[0] == '-' ? chars.length - 1 : chars.length;
if (chars[0] == '-') ans *= 1.5;
if ((chars[chars.length - 1] - '0') % 2 == 0) ans *= 2;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '2') two++;
}
ans *= two / length * 100;
System.out.printf("%.2f%%", ans);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
char[] chars = in.readLine().toCharArray();
double ans = 1, two = 0;
int length = chars[0] == '-' ? chars.length - 1 : chars.length;
if (chars[0] == '-') ans *= 1.5;
if ((chars[chars.length - 1] - '0') % 2 == 0) ans *= 2;
for (int i = 0; i < chars.length; i++) {
if (chars[i] == '2') two++;
}
ans *= two / length * 100;
System.out.printf("%.2f%%", ans);
}
}