tle了,看来i++明显不行,但又不知道怎么办,日后想办法改进
题目:
Once again Tavas started eating coffee mix without water! Keione told him that it smells awful, but he didn't stop doing that. That's why Keione told his smart friend, SaDDas to punish him! SaDDas took Tavas' headphones and told him: "If you solve the following problem, I'll return it to you."
The problem is:
You are given a lucky number n. Lucky numbers are the positive integers whose decimal representations contain only the lucky digits 4 and 7. For example, numbers 47, 744, 4 are lucky and 5, 17, 467 are not.
If we sort all lucky numbers in increasing order, what's the 1-based index of n?
Tavas is not as smart as SaDDas, so he asked you to do him a favor and solve this problem so he can have his headphones back.
The first and only line of input contains a lucky number n (1 ≤ n ≤ 109).
Print the index of n among all lucky numbers.
4
1
7
2
77
6
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
int n, counts;
scanf("%d", &n);
counts = 0;
for (int i = 1; i <= n; i++){
int p = 1,k = 1,weishu = 1;
for (int t = 1; t < 10; t++){
if (i >= k) weishu = t;
k *= 10;
}
int times = 1;
for (int j = 1; j <= weishu; j++){
int num = (i / times) % 10;
times *= 10;
if (num != 4 && num !=7){
p = 0;
break;
}
}
if (p == 1) counts++;
}
printf("%d", counts);
}
看了下别人思路竟然AC了= =主要是测得数据明显坑爹,否则我按题意是绝不会过的。
分析数的每个位置,7有2种情况,4有1种情况,在个位乘1,在十位乘2,在百位乘4,在千位乘8,大体是这思路
如77为2*2+2=6 , 47为1*2+2=4。
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
int n,counts = 0;
scanf("%d", &n);
int a[10];
int times = 1;
int len;
for (int i = 0;; i++){
int num = (n/times)%10;
times *= 10;
if (num == 0) {
len = i;
break;
}
else a[i] = num;
}
for (int i = 0; i < len; i++){
int k,t=1;
if (a[i] == 4) k = 1;
if (a[i] == 7) k = 2;
for (int p = 0; p < i; p++)
t *= 2;
counts += k * t;
}
printf("%d", counts);
}
//比如477就是 1*100+10*10+10= 1010 第10个
//4=1*1=1 第一个
//77=10*10+10=110 第六个
第二种思路,bfs 别人说是爆搜法
#include <stdio.h>
#include <queue>
#include <string.h>
using namespace std;
typedef struct{
long long int n;//爆数据
}node;
queue <node> q;
int main()
{
int x;
scanf("%d", &x);
node lucky;
lucky.n = 4;
q.push(lucky);
lucky.n = 7;
q.push(lucky);
int counts = 0;
while (!q.empty()){
node tmp = q.front();
q.pop();
if (tmp.n <= x){
node news;
news.n = tmp.n * 10 + 4;
q.push(news);
news.n = tmp.n * 10 + 7;
q.push(news);
counts ++;
}
}
printf("%d", counts);
}