如何通过 C# 使用回溯查找任何给定数字的幂?
创建一个求幂函数,该函数接收数字 x 和幂次 n,其中 x 为 2,n 为幂次。如果数字是偶数,那么我们必须执行 x*x,如果数字是奇数,则将结果乘以 x*x。继续递归调用,直到 n 为 0。
假设我们有一个数字为 2 和 8,则 2*2*2*2*2*2*2*2 = 256。
示例
using System;
namespace ConsoleApplication{
public class BackTracking{
public int FindPower(int x, int n){
int result;
if (n == 0){
return 1;
}
result = FindPower(x, n / 2);
if (n % 2 == 0){
return result * result;
}
else{
return x * result * result;
}
}
}
class Program{
static void Main(string[] args){
BackTracking b = new BackTracking();
int res = b.FindPower(2, 8);
Console.WriteLine(res);
}
}
}输出
256
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP