拜托大侠关于一个2的次方公式问题。。简单。 小弟数学差。啊55555在线等 输入一个N,用N判断是否为2的次方公式是什么。。??拜托。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 从2开始,不断乘以2,每次乘以次都和那个数N比较一下,如果最终跟N相等,那么N就是2的次方数,如果最后竟然超过了N,那么就不是。 就是写判断啊。就是 比如if (nXXXXXXXXX)如果是就YES。不是就N。 something likestatic bool IsPow2N(int n) { if (n<=0) return false; if (n==1) return true; if ((n % 2) != 0) return false; return IsPow2N(n/2); } 哦,sorry,应该从1开始,1是2的0此方。 555555555 thanks 思归 // 非递归的:using System;namespace Test{ class Test1 { public static bool IsPowerOf2(int n) { int i = 1; while(i <= n) { if(i == n) return true; i *= 2; } return false; } public static void Main() { int[] testData = {128, 256, 512, 1024, 2048, 255, 364, 555555, 520147}; foreach(int data in testData) { Console.WriteLine(data + ":\t" + (IsPowerOf2(data) ? "是" : "否")); } } }} 如果用TRY CATCH怎么写啊。。而且转换textbox.text 是用int parse吗。还是有其他方法 /steedhorse。。我是用textbox。。读出来付给N steedhorse。。55555帮帮小弟吧。弄个TEXTBOX版的 static bool IsPow2N(string n){ try { return IsPow2N(Int32.Parse(n)); } catch { return false; }} while(n%2==0&&n>1){n/=2;}if(n>1)return false;else retutn true; 如何解决Openfiledialog使用Dialogresult判定语句后,要点2次按钮才进行操作 烦...........................烦迷糊我了. 用new初始化对象的性能 关于Linq的小问题 送分问题!!!!!!!!! 为什么我无法声明System.Windows.Forms命名空间 问一个很愚蠢的问题,大家不要打击我。 webservice安全性问题 高手来救救偶~搞不定啊!!解决就给分啊!卡了一天了 C# 模拟多用户登录,出现超时诡异问题。求教。 treeView中怎么设置选中另一节点时将现在已展开的节点合拢 如何把文字保存成图片?
如果是就YES。不是就N。
{
if (n<=0)
return false; if (n==1)
return true; if ((n % 2) != 0)
return false; return IsPow2N(n/2);
}
using System;namespace Test
{
class Test1 { public static bool IsPowerOf2(int n) {
int i = 1;
while(i <= n) {
if(i == n)
return true;
i *= 2;
}
return false;
} public static void Main() {
int[] testData = {128, 256, 512, 1024, 2048, 255, 364, 555555, 520147}; foreach(int data in testData) {
Console.WriteLine(data + ":\t" + (IsPowerOf2(data) ? "是" : "否"));
}
}
}
}
{
try
{
return IsPow2N(Int32.Parse(n));
}
catch
{
return false;
}
}
{
n/=2;
}
if(n>1)return false;
else retutn true;