題目鏈接:
KY103 2的冪次方 https://www.nowcoder.com/share/jump/437195121691999575955
描述
??? Every positive number can be presented by the exponential form.For example, 137 = 2^7 + 2^3 + 2^0。 ??? Let's present a^b by the form a(b).Then 137 is presented by 2(7)+2(3)+2(0). Since 7 = 2^2 + 2 + 2^0 and 3 = 2 + 2^0 , 137 is finally presented by 2(2(2)+2 +2(0))+2(2+2(0))+2(0).? ? ??? Given a positive number n,your task is to present n with the exponential form?which only contains the digits 0 and 2.
輸入描述:
??? For each case, the input file contains a positive integer n (n<=20000).
輸出描述:
??? For each case, you should output the exponential form of n an a single line.Note that,there should not be any additional white spaces in the line.
中文描述:
每個正數都可以用指數形式表示。例如,137 = 2^7 + 2^3 + 2^0。我們用a(b)的形式表示a^b。那么137可以用2(7)表示 +2(3)+2(0)。 由于 7 = 2^2 + 2 + 2^0 和 3 = 2 + 2^0 ,因此 137 最終由 2(2(2)+2 +2(0))+2(2+2(0)) 表示 +2(0)。 給定一個正數 n,你的任務是將 n 以僅包含數字 0 和 2 的指數形式呈現。
輸入描述:
???? 對于每種情況,輸入文件都包含一個正整數 n (n<=20000)。
輸出描述:
???? 對于每種情況,您應該在一行中輸出 n 的指數形式。請注意,該行中不應有任何額外的空格。
示例1
輸入:
1315
輸出:
2(2(2+2(0))+2)+2(2(2+2(0)))+2(2(2)+2(0))+2+2(0)
思路:
-
首先,定義一個遞歸函數 powTwo,將數字 n 轉換為二進制形式,其中只有 0 和 1。
-
在遞歸函數中,處理二進制數,如果某一位為 1,則根據指數規則,將其轉換為對應的 2(a) 形式。
-
注意處理特殊情況,例如 2^1 直接表示為 "+2",其他情況通過遞歸處理更高次冪。
-
最后,去掉字符串開頭的 "+" 符號,即為所求的指數形式表示。
-
在 main 函數中,讀入輸入的正整數 n,并調用遞歸函數 powTwo 輸出結果。
源代碼:
#include <iostream>
#include <vector>
using namespace std;// 定義遞歸函數,將數字 n 轉換為指數形式
string powTwo(int n) {if (n == 0) {return "0";}if (n == 2) {return "2";}vector<int> nums;while (n != 0) {nums.push_back(n % 2); // 將 n 轉換為二進制n /= 2;}string res = "";for (int i = nums.size() - 1; i >= 0; i--) {if (nums[i] == 1) {if (i == 1) {res += "+2"; // 如果是 2^1,直接添加 "+2"}else {res += "+2(" + powTwo(i) + ")"; // 否則遞歸處理更高次冪}}}res.erase(0, 1); // 去掉最前面的 "+"return res;
}int main() {int n;while (cin >> n) {cout << powTwo(n) << endl;}return 0;
}
提交結果:
?