1 solutions

  • 0
    @ 2025-3-3 16:32:52

    C :

    #include<stdio.h>
    int main()
    {
    	int n,s=0,i=1,x;
    	scanf("%d",&n);
    	for(;i<=n;i++)
    	{	x=i;
    		do{
    		if(x%10==1)s++;
    		x=x/10;
    		}while(x!=0);
    	}
    	printf("%d",s);
     	return 0;
    }
    
    

    C++ :

    #include <bits/stdc++.h>
    using namespace std;
    
    int main(){
    	int i,g,s,b,q,n,c = 0;
    	cin>>n;
    	for(i = 1;i <= n;i++){
    		g = i % 10;
    		s = i / 10 % 10;
    		b = i / 100 % 10;
    		q = i / 1000;
    		
    		if(g == 1){
    			c++;
    		}
    		
    		if(s == 1){
    			c++;
    		}
    		
    		if(b == 1){
    			c++;
    		}
    		
    		if(q == 1){
    			c++;
    		}
    	}
    	
    	cout<<c<<endl;
    }
    
    

    Python :

    n = int(input())
    c = 0
    # 循环1~n
    for i in range(1, n + 1):
        # 对每个1~n的数拆位,看有多少个1,c+=1
        while i > 0:
            s = i % 10
            if s == 1:
                c += 1
            i //= 10
    print(c)
    
    • 1

    Information

    ID
    10444
    Time
    1000ms
    Memory
    32MiB
    Difficulty
    (None)
    Tags
    # Submissions
    0
    Accepted
    0
    Uploaded By