7 条回复
根据题主的思路,O(n) Java 写法 /** * 除 7,O(n)算法 */ import java.util.Scanner; public class Main3 { public static void main(String[] args) { Scanner cin = new Scanner(System.in); while(cin.hasNext()){ int n = cin.nextInt(); int[] a = new int[n]; int[] len = new int[n]; int[] count = new int[7]; //记录每个数mod 7 为0, 1, 2, ..., 6的分别有多少个 for(int i=0;i<n;i++){ long temp =cin.nextLong(); a[i] = (int) (temp % 7); len[i] = String.valueOf(temp).length(); count[a[i]] += 1; } int result = 0; //因为a[i] 肯定为0,..6中的一个,而计算是否被7整除,需要a[i],这里直接用j代替,就相当于遍历包含了当前 //元素的所有数(mod7),j中必有一个人等于a[i],所有减去自身(很巧妙) for(int i=0;i<n;i++){ for(int j=0;j<7;j++){ long temp = (long) (j*Math.pow(10, len[i])%7+a[i]); if (temp%7 == 0) { result += count[j]; if (j == a[i]) { //除去mod7 等于j(j中必有一数为a[i]) result -= 1; } } } } System.out.println(result); } } }
添加回复