JD16. 神奇数
描述
输入描述
输入包括一行,一行中两个整数l和r(1 ≤ l, r ≤ 10^9, 0 ≤ r - l ≤ 10^6),以空格分割输出描述
输出一个整数,即区间内的神奇数个数示例1
输入:
1 50
输出:
4
示例2
输入:
11 11
输出:
1
C++ 解法, 执行用时: 29ms, 内存消耗: 408KB, 提交时间: 2020-10-29
#include<bits/stdc++.h> using namespace std; bool Is_magic(int num[],int digit,int target){ for(int one=0;one<digit;one++){ if(num[one]==target) return 1; for(int two=one+1;two<digit;two++){ if(num[one]+num[two]==target) return 1; for(int three=two+1;three<digit;three++){ if(num[one]+num[two]+num[three]==target) return 1; for(int four=three+1;four<digit;four++){ if(num[one]+num[two]+num[three]+num[four]==target) return 1; for(int five=four+1;five<digit;five++){ if(num[one]+num[two]+num[three]+num[four]+num[five]==target) return 1; } } } } } return false; } int main(){ int l,r,ans=0; int num[11]={0}; cin>>l>>r; for(int i=l;i<r+1;i++){ int n = i; int digit = 0, suma = 0; while(n){ int tmp = n%10; num[digit++] = tmp; suma += tmp; n /= 10; } if(suma&1) continue; if(Is_magic(num,digit,suma>>1)) ans++; } cout<<ans; return 0; }
C++ 解法, 执行用时: 29ms, 内存消耗: 504KB, 提交时间: 2020-10-29
#include<bits/stdc++.h> using namespace std; bool Is_magic(int num[],int digit,int target){ for(int one=0;one<digit;one++){ if(num[one]==target) return 1; for(int two=one+1;two<digit;two++){ if(num[one]+num[two]==target) return 1; for(int three=two+1;three<digit;three++){ if(num[one]+num[two]+num[three]==target) return 1; for(int four=three+1;four<digit;four++){ if(num[one]+num[two]+num[three]+num[four]==target) return 1; for(int five=four+1;five<digit;five++){ if(num[one]+num[two]+num[three]+num[four]+num[five]==target) return 1; } } } } } return false; } int main(){ int l,r,ans=0; int num[11]={0}; cin>>l>>r; for(int i=l;i<r+1;i++){ int n = i; int digit = 0, suma = 0; while(n){ int tmp = n%10; num[digit++] = tmp; suma += tmp; n /= 10; } if(suma&1) continue; if(Is_magic(num,digit,suma>>1)) ans++; } cout<<ans; return 0; }