45.3和5(重要)

58 阅读1分钟

链接:ac.nowcoder.com/acm/problem…
来源:牛客网

题目描述

输出1~n中能被3整除,且至少有一位数字是5的所有整数.

输入描述:

输入一行,包含一个整数n。(1 <= n <= 100000)

输出描述:

输出所有满足条件的数,以换行隔开,具体见样例。

示例1

输入

50

输出

15
45

代码讲解

1.先写框架,并获取n的值

#include <bits/stdc++.h>

using namespace std;

int main(){
    int n;
    cin >> n;

    return 0;
}

2.从1到n遍历,并且n能被3整除

#include <bits/stdc++.h>

using namespace std;

int main(){
    int n;
    cin >> n;
    for(int i = 1;i <= n;i ++){
        if(i % 3 == 0){
        
        }
    }
    return 0;
}

3.定义一个变量来获取i的值,进而在定义一个变量获取i的各个位数,因为i的值不能随意改变

#include <bits/stdc++.h>

using namespace std;

int main(){
    int n;
    cin >> n;
    for(int i = 1;i <= n;i ++){
        if(i % 3 == 0){
            int temp = i;
            int g = temp % 10;
        }
    }
    return 0;
}

4.定义一个循环来逐次判断i的个位是否为5,如果是输出并停止该次循环,直接让i++;如果不是则自除,直至temp为0停止循环;

注意个位的数必须定义在while循环里面,不然只会判断一次

#include <bits/stdc++.h>

using namespace std;

int main(){
    int n;
    cin >> n;
    for(int i = 1;i <= n;i ++){
        if(i % 3 == 0){
            int temp = i;
           
            while(temp){
                int g = temp % 10;
                if(g == 5){
                    cout << i <<endl;
                    break;
                }
                temp /= 10;
            }
        }
    }
    return 0;
}