php实现 求int型数据在内存中存储时1的个数(函数都可自己实现)
生活随笔
收集整理的這篇文章主要介紹了
php实现 求int型数据在内存中存储时1的个数(函数都可自己实现)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
php實現 求int型數據在內存中存儲時1的個數(函數都可自己實現)
一、總結
一句話總結:函數我們自己都可以實現,尤其是很多基礎函數,沒有工具的時候自己寫。
?
1、php進制轉換函數?
base_convert進制轉換函數
5 $bin = base_convert($dec, 10, 2);;?
2、php十進制轉化成2進制函數?
dexbin,dex為10,bin,也很好記
3 $bin = decbin($input);?
3、php統計一個字符串中某字符出現的次數?
substr_count()
6 echo substr_count($bin, "1").PHP_EOL;?
?
?
二、求int型數據在內存中存儲時1的個數
題目描述
輸入一個int型的正整數,計算出該int型數據在內存中存儲時1的個數。
輸入描述:
?輸入一個整數(int類型)
輸出描述:
?這個數轉換成2進制后,輸出1的個數
示例1輸入
復制 5輸出
復制 2?
代碼:
1 <?php 2 $input = intval(trim(fgets(STDIN))); 3 $output = 0; 4 while(0 < $input){ 5 if(1 == $input%2) 6 $output++; 7 $input = floor($input/2); 8 } 9 echo $output;?
1 <?php 2 $dec = ""; 3 $bin = ""; 4 fscanf(STDIN, "%s", $dec); 5 $bin = base_convert($dec, 10, 2);; 6 echo substr_count($bin, "1").PHP_EOL;?
1 <?php 2 $input = trim(fgets(STDIN)); 3 $bin = decbin($input); 4 echo substr_count($bin, '1');?
decbin?—?十進制轉換為二進制
string?decbin?(?int?$number?)
?
?
?
總結
以上是生活随笔為你收集整理的php实现 求int型数据在内存中存储时1的个数(函数都可自己实现)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php 简单路由实现
- 下一篇: 业内首创普惠保险,看国泰产险如何借助数据