当前位置: 代码迷 >> 综合 >> L1-017.到底有多二
  详细解决方案

L1-017.到底有多二

热度:22   发布时间:2023-11-03 00:20:07.0

L1-017. 到底有多二

时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越

一个整数“犯二的程度”定义为该数字中包含2的个数与其位数的比值。如果这个数是负数,则程度增加0.5倍;如果还是个偶数,则再增加1倍。例如数字“-13142223336”是个11位数,其中有3个2,并且是负数,也是偶数,则它的犯二程度计算为:3/11*1.5*2*100%,约为81.82%。本题就请你计算一个给定整数到底有多二。

输入格式:

输入第一行给出一个不超过50位的整数N。

输出格式:

在一行中输出N犯二的程度,保留小数点后两位。

输入样例:
-13142223336
输出样例:
81.82%

提交代码

我的代码1:

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{long long n,t;int cnt1=0,cnt2=0;double res=1;cin>>n;t=n;if(t<0){t=-t;res*=1.5;}if(t%2==0){res*=2;}while(t){cnt1++;if(t%10==2)cnt2++;t/=10;}res*=cnt2*1.0/cnt1;res*=100;printf("%.2lf%%\n",res);return 0;
}
这题提交上去只得了11分,有两个测试点没过。

我的第一个代码是用long long来存储n的,long long各种数据类型的存储范围 最多存19位,n最多可以是50位,所以用long long存储空间显然不够。

用字符数组来存储试试,,,

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;char str[55];
int main()
{int cnt1=0,cnt2=0;double res=1;cin>>str;if(str[0]=='-'){res*=1.5;cnt1=strlen(str)-1;}elsecnt1=strlen(str);if((str[strlen(str)-1]-'0')%2==0)res*=2;for(int i=0;i<strlen(str);i++){if(str[i]=='2')cnt2++;}res*=cnt2*1.0/cnt1;res*=100;printf("%.2lf%%\n",res);return 0;
}



  相关解决方案