使用幂的角数字组成数字
什么是角数字?
数字的角数字是指最右边和最左边的数字。
例如,1234 的角数字是 1 和 4。
一位数的角数字将是该数字的两倍。
例如,2 的角数字将是 2 和 2。
问题陈述
对于给定的两个数字 n 和 x,使用 1 和 x 中所有 n 的幂的角数字组成一个数字,即 n1, n2....nx.
示例
输入:n = 2, x = 4 输出:22448816
解释
21= 2. 角数字 = 2, 2. 22 = 4. 角数字 = 4, 4. 23 = 8. 角数字 = 8, 8. 24 = 16. 角数字 = 1, 6.
因此,由上述所有数字的角数字组成的数字是22448816。
输入:n = 16,x = 5 输出:1626466616
解释
161 = 16. Corner digits = 1, 6. 162 = 256. Corner digits = 2, 6. 163 = 4096. Corner digits = 4, 6. 164 = 65536. Corner digits = 6, 6. 165 = 1048576. Corner digits = 1, 6.
因此,由上述所有数字的角数字组成的数字是 1626466616。
算法
逐一找出 N 从 1 到 X 的所有幂。
将幂存储在 power 数组中。
创建一个 answer 数组用于存储最终输出。
将 power 数组的第一个和最后一个数字存储在 answer 数组中。
打印 answer 数组。
伪代码
Function main() −
从用户那里获取 n 和 x 的输入。
函数调用 corner_digits_number()。
Function corner_digits_number(int n, int x) −
创建向量 power 和 answer,分别用于存储幂和最终答案。
将 1 存储在 power 中。(n 的幂为 0)。
对于 i=1 到 i=x −
函数调用 store_next_power()
将 power 的最后一位数字存储在 answer 中。
将 power 的第一位数字存储在 answer 中。
Function call print_output().
Function store_next_power(vector<int>&power, int n) −
Initialize carry = 0, product = 1.
For i=0 to i=power.size()-1 −
Product -> power[i] * n + carry.
power[i] -> product %10.
carry -> product/10.
while carry is not equal to zero −
Store carry % 10 in power.
carry -> carry /10.
Function print_output(vector<int>answer) −
For i=0 to i=answer.size()-1 −
Print answer[i].
示例
下面是一个 C++ 程序,用于从 1 到 x 的所有 n 幂的角数字组成一个数字。
#include<iostream> #include<vector> using namespace std; //此函数计算下一个幂值并将其存储在幂向量中 void store_next_power(vector<int>&power, int n){ int carry = 0, product; for(int i=0 ; i < power.size() ; i++){ //计算 n 的幂 product = ( power[i] * n ) + carry; //存储特定索引的幂的数字 power[i] = product % 10 ; //进位将添加到下一个索引的值。 carry = product / 10 ; } //进位也将添加到幂向量。 while(carry){ power.push_back(carry % 10); carry = carry / 10 ; } } //打印最终输出 void print_output(vector<int>v){ for(int i=0 ; i < v.size() ; i++){ cout<<v[i]<<", "; } } //此函数打印由 1 到 x 的所有 n 的幂的角数字组成的数字。 void corner_digits_number(int n, int x){ //用于存储幂的向量 vector<int>power; //存储 n 的 0 次幂。 //这将有助于找到 n 的下一个幂。 power.push_back(1); //用于存储最终输出的向量 vector<int>answer; //从 1 和 x 计算 n 的所有幂 for(int i=0 ; i < x ; i++){ //函数调用用于存储下一个幂值 //在向量中 store_next_power(power,n); //将幂向量中的第一个和最后一个数字添加到答案向量中 //幂中的最后一位首先被推送到答案向量中 //因为它包含个位值。 answer.push_back(power.back()); answer.push_back(power.front()); } //函数调用用于打印最终数字。 print_output(answer); } int main(){ int n = 6, x = 4; //函数调用打印所需数字 cout<< "n=6 和 x =4 的角数字为: "<<endl; corner_digits_number(n,x); return 0; }
输出
n=6 和 x =4 的角数字为: 6, 6, 3, 6, 2, 6, 1, 6,
本文讨论使用 1 到 x 的所有 n 幂的角数字形成数字的问题。 n 和 x 是问题中的两个给定数。
首先通过几个例子解释该问题,然后讨论方法。
文章中给出了算法、伪代码和 C++ 程序。还提到了时间和空间复杂度。