快速幂!!

版权声明:个人做题总结专用~ https://blog.csdn.net/tb_youth/article/details/84872461

zcmu:
1605: 大一下之小试身手
Time Limit: 1 Sec Memory Limit: 128 MB
[Submit][Status][Web Board]
Description

在浙江中医药大学的半年学习,你看起来帅了很多,这个时候你已经看不上A+B了,现在你喜欢用你的代码去模拟你看到一切的事物。有一天你发现了一门神奇的语言那就是python,比如print “xxxx”*100,就可以把”xxxx”连续输出一百遍… 这个时候你表示不服,我的C语言也可以,不就是多写一个循环而已么。不开心的你于是决定用C模拟Python解释器,考虑到… 其实也没啥,现在我告诉你Python的一些常用的运算符号和规则,你来做个解释器,恩,就这样。

在Python里 “*”,”+”,”/”, ”-”,”%” 和C语言一样

”表示幂运算,比如23==8

给你的语句如下:

Print string * num(string表示一个字符串,num表示一个数)

Print a operator b ( 输出a ,b经过operator运算的结果)

Input

只有上述两种输入(数据在Long long 内)

Output

输出正确的答案

Sample Input

print 54*1
print “Tomcat”*2

Sample Output

54
TomcatTomcat

HINT

Source
/这题对于幂运算如果用math里的自带的pow,wrong的会不想说话!!
(比如2
*-3,用math里的pow答案会是0,但是实际AC的是不输出,而且不知道为什么也输不了下一组了)
写这题学到了快速幂,我也不亏,虽然wrong到我心碎
*/
AC_code:

#include <stdio.h>
#include <string.h>
#define ll long long
char a[10000],b[10000];
ll Pow(ll a,ll b)//快速幂
{
	ll ans=1;
	while(b)
	{
		if(b&1)ans*=a;
		a*=a;
		b>>=1;
	}
	return ans;
}
int main()
{
    while(gets(a))
    {
        int len_a= strlen(a),l = 0,i = 6;
        if(a[i]=='"')
        {
            memset(b,'\0',sizeof(b));
            if(a[i]=='"')
		   {
			i++;
			while(a[i]!='"')
			{
				b[l++]=a[i];
				i++;
			}
		   }
		    i += 2;
            int num = 0;
            for(; i <  len_a; i++)
                num = num*10 + (a[i]-'0');
            while(num--)
            {
                printf("%s",b);
            }
            printf("\n");
        }
        else
        {
            long long ans,num1=0,num2=0;
            int n = 1,flag = 0;
            if(a[i]=='-')
            {
                n = -1;
                i++;
            }
            while(a[i]>='0'&&a[i]<='9')
            {
                num1 = num1*10 + (a[i]-'0');
                i++;
            }
            num1 *= n;
            n = 1;
            char m = a[i];
            if(a[i+1]=='*')
            {
                i++;
                flag = 1;
            }
            i++;
            if(a[i]=='-')
            {
                n = -1;
                i++;
            }
            while(a[i]>='0'&&a[i]<='9')
            {
                num2 = num2*10 + (a[i]-'0');
                i++;
                if(i >=len_a) break;
            }
            num2 *= n;
            if(flag)
               ans = Pow(num1,num2);
            else
            {
                switch(m)
                {
                case '+':ans = num1 + num2;break;
                case '-':ans = num1 - num2;break;
                case '*':ans = num1 * num2;break;
                case '/':ans = num1 / num2;break;
                case '%':ans = num1 % num2;break;
                }
            }
             printf("%lld\n",ans);
    }
}
return 0;
}

猜你喜欢

转载自blog.csdn.net/tb_youth/article/details/84872461