L1-022 奇偶分家 - java

题目解析

输出给定的n个数中 求出 奇偶个数分别有多少个

解题思路

可以利用位运算 (x&1)==1(x \& 1) == 1 判断是否为奇数
或者利用取余运算 (x%2)==1(x \% 2) == 1 判断是否为奇数

代码

位运算

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

public class Main
{

	public static void main(String[] args)
	{
		int n = sc.nextInt();

		int ji = 0, ou = 0;
		while (n-- > 0)
		{
			int x = sc.nextInt();
			if ((x & 1) == 1)
				ji++;
			else
				ou++;
		}
		out.println(ji + " " + ou);

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

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

取余运算


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

public class Main
{

	public static void main(String[] args)
	{
		int n = sc.nextInt();

		int ji = 0, ou = 0;
		while (n-- > 0)
		{
			int x = sc.nextInt();
			if (x % 2 == 1)
				ji++;
			else
				ou++;
		}
		out.println(ji + " " + ou);

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

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


位运算


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

赞赏