题目1095:2的幂次方

http://ac.jobdu.com/problem.php?pid=1095

这个题主要需要注意输出时的括号匹配

View Code
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<string>
 4 #include<stack>
 5 
 6 using namespace std;
 7 int mycount=0;
 8 stack<int> intStack;
 9 
10 void f(int n)
11 {
12     int m,num=-1;
13     while( n)
14     {
15         m=n%2;
16         n/=2;
17         ++num;
18         if(m==1)
19         {
20             intStack.push(-1);
21             intStack.push(num);
22             ++mycount;
23         }
24     }
25 }
26 void f1(int n)
27 {
28     int m,num=-1;
29     while(n)
30     {
31         m=n%2;
32         n/=2;
33         ++num;
34         if(m==1)
35         {
36             intStack.push(num);
37         }
38     }
39 }
40 void print()
41 {
42     int num;
43     num=intStack.top();
44     intStack.pop();
45     while(num!=-1)
46     {
47         if(num>2)
48         {
49             cout<<"2(";//------左括号
50             intStack.push(-1);
51             f1(num);
52             print();
53             cout<<")";//---右括号
54         }
55         else
56         {
57             if(num==1)
58                 cout<<"2";
59             else
60                 cout<<"2("<<num<<")";
61         }
62         num=intStack.top();
63         if(num!=-1)
64             cout<<"+";
65         intStack.pop();
66     }
67 }
68 
69 int main()
70 {
71     int n,i;
72     while(cin>>n)
73     {
74         mycount=0;
75         f(n);
76         for(i=0;i<mycount;++i)
77         {
78             if(i!=0)
79                 cout<<"+";
80             print();
81             
82         }
83         cout<<endl;
84     }
85     return 0;
86 }

 

 

posted @ 2013-01-19 14:31  dupuleng  阅读(125)  评论(0)    收藏  举报