链接:https://ac.nowcoder.com/acm/contest/5674/A
来源:牛客网
题意:
给你一个字符串,里面只存在0,2,(,),+这几个字符,问你这个字符串是由那个数分解而来的
a(b)代表a的b次,而b这个数又是由若干个数相加
##solution:
我们将字符串转换为数字,字符数字转换为对应的数字,计‘(’为-1,依次入栈,如果碰到有括号,则往前出栈直到出栈的值为-1,这些出栈的数字相加,然后再取出前面一个数,快速幂求其那个数的幂次
就是模拟一下出栈和入栈,在出栈过程中求和,并求出幂次的过程
import java.math.BigInteger;
import java.util.Scanner;
import java.util.Stack;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s;
s=in.next();
Stack<BigInteger> st=new Stack<BigInteger>();
quick q=new quick();
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)>='0'&&s.charAt(i)<='9')
st.push(BigInteger.valueOf(s.charAt(i)-'0'));
else if(s.charAt(i)=='(')
st.push(BigInteger.valueOf(-1));
else if(s.charAt(i)==')')
{
BigInteger num=st.pop();
while(!st.isEmpty())
{
BigInteger qaq1=st.pop();
if(qaq1.equals(BigInteger.valueOf(-1))==true)break;
num=num.add(qaq1);
}
BigInteger di=st.pop();//System.out.println(di+" "+num);
num=q.fpow(di, num);
st.push(num);
//System.out.println(num);
}
//System.out.println(st.peek());
}
BigInteger big=st.pop();
while(!st.isEmpty())
{
BigInteger qaq1=st.pop();
if(qaq1.equals(BigInteger.valueOf(-1))==true)break;
big=big.add(qaq1);
}
System.out.println(big);
}
}
class quick{
BigInteger fpow(BigInteger a,BigInteger x)
{
BigInteger ans=BigInteger.valueOf(1);
while(x.equals(BigInteger.valueOf(0))==false)
{
if(x.mod(BigInteger.valueOf(2)).equals(BigInteger.valueOf(1))==true)ans=ans.multiply(a);
a=a.multiply(a);
x=x.divide(BigInteger.valueOf(2));
//System.out.println(ans);
}
return ans;
}
}



京公网安备 11010502036488号