進位制轉換

fufuaifufu發表於2024-11-20

504.七進位制數
題目連結:https://leetcode.cn/problems/base-7/description/
題解程式碼:

class Solution {
public:
    string convertToBase7(int num) {
        string nums;
        int a=abs(num);
        if(a==0)  return "0";
        while(a>0){
            nums.push_back(a%7+'0');
            a/=7;
        } 
        if(num<0) nums.push_back('-');
        reverse(nums.begin(),nums.end());
        return nums;
    }
};

1837.k進製表示下的各位數字總和
題目連結:https://leetcode.cn/problems/sum-of-digits-in-base-k/
題解程式碼:

class Solution {
public:
    int sumBase(int n, int k) {
        int m=0;
        while(n){
            m+=n%k;
            n/=k;
        }
        return m;
    }
};

相關文章