Leetcode PHP题解--D57 762. Prime Number of Set Bits in Binary Representation
生活随笔
收集整理的這篇文章主要介紹了
Leetcode PHP题解--D57 762. Prime Number of Set Bits in Binary Representation
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
D57 762. Prime Number of Set Bits in Binary Representation
題目鏈接
762. Prime Number of Set Bits in Binary Representation
題目分析
對給定范圍內的每個整數,返回其二進制形式下,數字1出現的次數為質數的次數。
例如11111,1出現了5次,5是質數。
再如10111,1出現了4次,4不是質數。
思路
由于題目固定了范圍為1~10^6,10^6次方為1千萬。小于2^24。即最多只會出現24次1。
由于小于24的質數個數有限,我們直接寫死24以內的質數。
對每一個數字,計算1出現的次數。再判斷出現次數是否在這個質數數組內。
存在則符合題目要求的數字,否則不計入該數字。
最終代碼
<?php class Solution {/*** @param Integer $L* @param Integer $R* @return Integer*/function countPrimeSetBits($L, $R) {$primes = [2,3,5,7,11,13,17,19,23];$nums = range($L,$R);$primeOnes = 0;foreach($nums as $num){$ones = array_filter(str_split(decbin($num)), function($val){return $val == '1';});if(in_array(count($ones),$primes)){$primeOnes++; }}return $primeOnes;} }若覺得本文章對你有用,歡迎用愛發電資助。
轉載于:https://my.oschina.net/u/2246923/blog/3047838
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的Leetcode PHP题解--D57 762. Prime Number of Set Bits in Binary Representation的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Electron】Error: A d
- 下一篇: new Date(2019-05-10