吉利数——字符串思想和逐位分解保留思想(Java/C++)

安徽大学算法期末机试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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

向光.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值