求一个数内含1个次数
import java.util.regex.Matcher; import java.util.regex.Pattern; /****
****author :hxy
****
****/
public class Test { private final int n; public int cnt_all; public Test(int n) { this.n = n; cnt_all = 0; } // 分多个线程计算 public void binaryHandlerN(int threadNum) { int gap = n / threadNum; int tmp = 0; do { Thread t = new Thread(new _handler(tmp + 1, tmp + gap)); tmp = tmp + gap; t.run(); } while (tmp < n); } // 匹配每个数有几个1 private int rexStr(int i) { int cntForEachNum = 0; Matcher m = Pattern.compile(String.valueOf(1)).matcher(String.valueOf(i)); while (m.find()) { cntForEachNum++; } return cntForEachNum; } class _handler implements Runnable { int cnt = 0; int num1 = 0; int num2 = 0; public _handler(int num1, int num2) { this.num1 = num1; this.num2 = num2; if (num2 > n) { this.num2 = n; } } @Override public void run() { int cnt = 0; for (int i = num1; i <= num2; i++) { cnt = cnt + rexStr(i); } cnt_all = cnt + cnt_all; } } public static void main(String[] args) { Test t = new Test(44); t.binaryHandlerN(5); System.out.println("1重复的次数为:" + t.cnt_all); } }
计划、执行、每天高效的活着学着