纯纯的暴力做法,众所不周知,暴力是不需要考虑时间复杂度的,所以就会有一种神奇的暴力做法。
由于数字都是八位数,就把它的每一个数位都问候一遍,由此可以做出一个 check 函数:
check 函数的思路: 用 x_1 到 x_8 来记录我要判断的数的每个数位是多少,再用字符串把我的数字改为字符形式,再用 string 专属函数 find 来分别找 、、、,若都有,返回 ,否则返回 。
C++
int check(int x){
int x_1,x_2,x_3,x_4,x_5,x_6,x_7,x_8;
x_8=x%10;
x_7=x/100%10;
x_6=x/1000%10;
x_5=x/10000%10;
x_4=x/100000%10;
x_3=x/1000000%10;
x_2=x/10000000%10;
x_1=x/100000000%10;
string s;
s=x_1+'0',s+=x_2+'0',
s+=x_3+'0',s+=x_4+'0',
s+=x_5+'0',s+=x_6+'0',
s+=x_7+'0',s+=x_8+'0';
for(int i=0;i<8;i++){
if(s.find('2')!=s.npos) i=s.find('2');
else{return 1;}
if(s.find('0')!=s.npos) i=s.find('0');
else{return 1;}
if(s.find('2')!=s.npos) i=s.find('2');
else{return 1;}
if(s.find('3')!=s.npos) i=s.find('3');
else{return 1;}
}return 0;
}Python
def check(x):
s = f"{x:08d}"
# 按顺序检查子序列
try:
pos = s.index('2')
pos = s.index('0', pos+1)
pos = s.index('2', pos+1)
pos = s.index('3', pos+1)
return 0
except ValueError:
return 1
再加一个循环问候 至 全家,就出现一个总代码。
Code:
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod=1e9+7;
int check(int x){
int x_1,x_2,x_3,x_4,x_5,x_6,x_7,x_8;
x_8=x%10;
x_7=x/100%10;
x_6=x/1000%10;
x_5=x/10000%10;
x_4=x/100000%10;
x_3=x/1000000%10;
x_2=x/10000000%10;
x_1=x/100000000%10;
string s;
s=x_1+'0',s+=x_2+'0',
s+=x_3+'0',s+=x_4+'0',
s+=x_5+'0',s+=x_6+'0',
s+=x_7+'0',s+=x_8+'0';
for(int i=0;i<8;i++){
if(s.find('2')!=s.npos) i=s.find('2');
else{return 1;}
if(s.find('0')!=s.npos) i=s.find('0');
else{return 1;}
if(s.find('2')!=s.npos) i=s.find('2');
else{return 1;}
if(s.find('3')!=s.npos) i=s.find('3');
else{return 1;}
}return 0;
}signed main(){
ios::sync_with_stdio(0),
cin.tie(0),cout.tie(0);
int ans=0;
for(int i=12345678;i<=98765432;i++)
if(check(i)) ans++;
cout<<ans;
return 0;
}Python
def check(x):
# 将数字格式化为8位字符串(自动补前导零)
s = f"{x:08d}"
# 顺序查找子序列 2->0->2->3
try:
pos = s.index('2') # 找第一个2
pos = s.index('0', pos+1) # 在第一个2之后找0
pos = s.index('2', pos+1) # 在0之后找第二个2
pos = s.index('3', pos+1) # 在第二个2之后找3
return 0 # 找到完整序列
except ValueError:
return 1 # 未找到
def main():
count = 0
# 遍历所有8位数(包含端点)
for num in range(12_345_678, 98_765_432 + 1):
if check(num):
count += 1
print(count)
if __name__ == "__main__":
main()
时间非常快(不建议 直接 使用),只需几个小时反正得出答案是 。
再来个答案输出。
Code:
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod=1e9+7;
signed main(){
ios::sync_with_stdio(0),
cin.tie(0),cout.tie(0);
cout<<"85959030";
return 0;
}Python
print("85959030")