安徽大学算法期末机试3262题
题解:
最直观的思路便是直接利用字符串的contains特性,直接将数字转换为字符串,直接判断其是否含有7和13子串即可,但会超时;
java代码:
import java.util.Scanner;
class Test1{
static int count = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int m = scanner.nextInt();
int n = scanner.nextInt();
solve(m,n);
}
static boolean check2(int i){
String s = String.valueOf(i);
if(!s.contains("13"))
{
return true;
}
else{
return false;
}
}
static boolean check1(int i){
while(i>0){
int temp = i%10;
if(temp==4){
return false;
}
i/=10;
}
return true;
}
public static void solve(int m,int n){
for(int i=m;i<=n;i++){
if(check1(i) && check2(i)){
count++;
}
}
System.out.print(count);
}
}
C++代码:
#include<iostream>
#include<string>
#include<stdio.h>
using namespace std;
int m;
int n;
int count = 0;
bool check2(int i){
string s = to_string(i);
string::size_type idx;
idx = s.find("13");
if(idx == string::npos )//不存在
{
return true;
}
else{
return false;
}
}
bool check1(int i){
while(i){
int temp = i%10;
if(temp==4){
return false;
}
i/=10;
}
return true;
}
void solve(){
for(int i=m;i<=n;i++){
if(check1(i) && check2(i)){
count++;
}
}
printf("%d",count);
}
int main(){
scanf("%d %d",&m,&n);
solve();
return 0;
}
思考:
为了不超时,舍弃了字符串的思想,我们可以还是按照判断7一样,对13也进行判断,即我们对所给数字进行逐位分解,不同于以前的是,我们在判断是否含有13时,在拿到一位的数字后要先保留下来,等拿到第二个数字时将原先保存的拿出来一起进行判断,这便是对于二位数的是否含有进行的判断,即利用先保存的一个思想。
代码:
#include<iostream>
using namespace std;
int fun4(long long x){
int flag = 0;
while(flag==0 && x>0){
if(x%10==4){
flag = 1;
}else{
x /= 10;
}
}
return flag;
}
int fun13(long long x){
int flag = 0;
int last = 0;
while(flag==0 && x>0){
if(x%10==1 && last==3){
flag = 1;
}else{
last = x % 10;
x /= 10;
}
}
return flag;
}
int main ()
{
long long m, n;
long long count = 0;
cin >> m >> n;
for (long long i = m; i <= n;i++){
if(fun4(i)||fun13(i)){}
else count++;
}
cout << count+1;
return 0;
}