L1-017 到底有多二 - java

题目解析

输出 2 占 总数字字符的比例 且 负数多0.5倍 偶数再加1倍

解题思路

暴力枚举字符串中含有多少个二 再利用题意求出答案即可
切记 '-' 不算在总长度中

代码

import java.io.*;
import java.util.*;

public class Main
{

	public static void main(String[] args)
	{
		char s[] = sc.next().toCharArray();
		int len = s.length;

		double cd = 1;
		boolean fu = false;
		if (s[0] == '-')
		{
			cd += 0.5;
			fu = true;
		}

		if (((s[len - 1] - '0') & 1) == 0)
			cd *= 2;

		int two = 0;
		for (int i = 0; i < len; i++)
		{
			if (s[i] == '2')
				two++;
		}

		if (fu)
			len--;

		double ans = two * 1.0 / len * cd;
		out.printf("%.2f%%\n", ans * 100);

		out.flush();
		out.close();
	}

	static Scanner sc = new Scanner(System.in);
	static PrintWriter out = new PrintWriter(System.out);
}

团体程序设计天梯赛-练习集-java

赞赏