Exponentiation--POJ 1001

1、题目类型:数论、大数乘法。

2、解题思路:二分计算提高运算速度:n表示为2的0、1、2、3...次幂的之和。

3、注意事项:测试数据中00.00的情况;注意 . 的位置。

4、实现方法:(C++)

  
    
#include < iostream >
#include
< string >
#include
< algorithm >
using namespace std;

string ans;

string Solve( string str1, string str2)
{
int len1 = str1.length();
int len2 = str2.length();
int i,j,a,b;
string str = "" ;
int tmp[ 1000 ];

reverse(str1.begin(),str1.end());
reverse(str2.begin(),str2.end());
memset(tmp,
0 , sizeof (tmp));
for (i = 0 ;i < len1;i ++ )
{
for (j = 0 ;j < len2;j ++ )
{
a
= str1[i] - ' 0 ' ;
b
= str2[j] - ' 0 ' ;
tmp[i
+ j] += a * b;
}
}
for (i = 0 ;i < len1 + len2 - 1 ;i ++ )
{
a
= tmp[i] % 10 ;
b
= tmp[i] / 10 ;
tmp[i]
= a;
tmp[i
+ 1 ] += b;
}
if (b > 0 )
i
++ ;
for (j = 0 ;j < i;j ++ )
str
+= tmp[j] + ' 0 ' ;
reverse(str.begin(),str.end());
return str;
}

void Cal( string str, int n)
{
ans
= " 1 " ;
while (n)
{
if (n & 1 )
ans
= Solve(ans,str);
str
= Solve(str,str);
n
= n >> 1 ;
}
}

int main()
{
string str;
int i,n,pos,step = 0 ;
while (cin >> str >> n)
{
pos
=- 1 ;
for (i = 0 ;i < str.length();i ++ )
{
if (str[i] == ' . ' )
{
pos
= i;
break ;
}
}
if (pos !=- 1 )
{
step
= str.length() - pos - 1 ;
str.erase(str.begin()
+ pos);
}
for (i = 0 ;i < str.length();i ++ )
{
if (str[i] != ' 0 ' )
break ;
}
if (i == str.length())
{
cout
<< 0 << endl;
continue ;
}
Cal(str,n);
string s = "" ;
int flag = 0 ;
int flag1 = 0 ;
reverse(ans.begin(),ans.end());
for (i = 0 ;i < ans.length();i ++ )
{
if ( ! flag1)
{
if ((step && i == step * n))
{
if (flag)
s
+= ' . ' ;
flag1
= 1 ;
}
}
if ( ! flag &&! flag1)
{
if (ans[i] != ' 0 ' )
{
s
+= ans[i];
flag
= 1 ;
}
}
else
{
s
+= ans[i];
}
}
if ( ! flag1 && i <= step * n)
s
+= ' . ' ;
reverse(s.begin(),s.end());
while (s[ 0 ] == ' 0 ' )
{
s.erase(s.begin());
}
cout
<< s << endl;
}
return 0 ;
}

5、实现方法:(java)

  
    
import java.util. * ;
import java.math. * ;
public class Main
{
public static void main(String[] args)
{
Solve slv
= new Solve();
slv.Do();
}
}

class Solve
{
Scanner cin
= new Scanner(System.in);
String a,s;
int n,start,len,tmp;

void Do()
{
while (cin.hasNext())
{
boolean flag = true ;
a
= cin.next();
n
= cin.nextInt();

Double dd
= new Double(a);
if (dd.intValue() == dd.doubleValue())
flag
= false ;

BigDecimal bigd
= new BigDecimal(a);
s
= bigd.pow(n).toPlainString();

if (flag == true )
{

start
= 0 ;
if (s.charAt( 0 ) == ' 0 ' && s.charAt( 1 ) == ' . ' )
start
= 1 ;

len
= s.length() - 1 ;
while (len >= 0 && s.charAt(len) == ' 0 ' )
len
-- ;
s
= s.substring(start,len + 1 );
}
else
{
len
= s.length() - 1 ;
while (len >= 0 && s.charAt(len) != ' . ' )
len
-- ;
if (len >= 0 )
s
= s.substring( 0 ,len);
}
if (s.length() == 0 )
s
= " 0 " ;
System.out.println(s);
}
}
}

 

 

 

 



 

你可能感兴趣的:(exp)