再刷PAT系列~一的個數

題目描述
NowCoder總是力爭上游,凡事都要拿第一,所以他對“1”這個數情有獨鍾。愛屋及烏,他也很喜歡包含1的數,例如10、11、12……。不僅如此,他同樣喜歡任意進制中包含1的數。當然,其中包含1的個數越多他越喜歡。你能幫他統計一下某個數在特定的進制下1的個數嗎?

輸入描述:
輸入有多組數據,每組數據包含一個正整數n (1≤n≤2147483647)和一個正整數r (2≤r≤16)。

其中n爲十進制整數,r爲目標進制。

輸出描述:
對應每組輸入,輸出整數n轉換成r進制之後,其中包含多少個“1”。

輸入例子:

1 2
123 16

輸出例子:

1
0

分析:典型的進制轉換問題,但在本題不需求出轉換後的結果,利用短除法,統計餘數爲1的情況即可。。。。

編碼實現:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while(scanner.hasNext()){
            int ten = scanner.nextInt(); // 十進制
            int other = scanner.nextInt(); // 其他進制
            int count = transferOther(ten,other);
            System.out.println(count);
        }
    }
    private static int transferOther(long ten, int other) {
        long shang = -1;
        long yushu = -1;
        int count = 0;
        while(shang!=0){
            shang = ten/other;
            yushu = (int)ten%other;
            if (yushu == 1) {
                count++;
            }
            ten = shang;
        }
        return count;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章