【位运算】C_009_LQ_完美运算(三进制)

一、Problem

在这里插入图片描述

472701

二、Solution

方法一:三进制

可以先打表,即预处理 [1, 2020] 中的每个数的 a1 和 a2,分别保存到两个数组中…

import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static class Solution {
		int[] A(int x) {
			int x1 = 0, x2 = 0;
			while (x != 0) {
				if (x % 3 == 1) x1++;
				if (x % 3 == 2) x2++;
				x /= 3;
			}
			return new int[]{x1, x2};
		}
		void init() {
			Scanner sc = new Scanner(new BufferedInputStream(System.in));
			BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
			long cnt = 0;
			for (int i = 1; i <= 2020; i++)
			for (int j = i; j <= 2020; j++) {
				int[] a1 = A(i);
				int[] a2 = A(j);
				if (Math.abs(a1[0]-a1[1]) == Math.abs(a2[0] - a2[1]))
					cnt++;
			}
			System.out.println(cnt);
		}
	}
    public static void main(String[] args) throws IOException {  
        Solution s = new Solution();
		s.init();
    }
}
原创文章 787 获赞 314 访问量 5万+

猜你喜欢

转载自blog.csdn.net/qq_43539599/article/details/105847783