Numbers for which no three consecutive digits have a sum greater than a given value
Both the solutions fail the time limit.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
/*
* Cpp Version of the problem:
* "Numbers for which no three consecutive digits
* have a sum greater than a given value"
*
*/
int main() {
int n=9;
int dig;
// cout<<"What's dig? ";
cin>>dig;
// cout<<endl;
string st="";
for(int i=0;i<dig;i++){
if(i==0){
st+="1";
}
else{
st+="0";
}
}
int ans_count=0;
// cout<<"st is "<<st<<endl;
// cout<<"Length of st is "<<st.size()<<endl;
int num=stoi(st);
// Now we have our base number
while(st.size()==dig){
int chk=1;
// cout<<"st is "<<st<<endl;
for(int i=0;i<dig-2;i++){
int sum=(int(st[i])-48)+(int(st[i+1])-48)+(int(st[i+2])-48);
if(sum>n){
chk=0;
break;
}
}
if(chk==1){
ans_count++;
}
num+=1;
st=to_string(num);
}
cout<<ans_count<<endl;
return 0;
}
/*****************/
'''
Python Version of the problem:
Numbers for which no three consecutive digits
have a sum greater than a given value
'''
n=9
dig=int(input())
# Firstly generate a base 20 digit number
l=["1" if i==0 else "0" for i in range(dig)]
st="".join(l)
num=int(st)
# print(num)
ans_count:int=0
# print(len(st)==dig)
while(len(st)==dig):
# print(st)
chk=1
# if('9' in list(st)):
# print("Current number has 9 in it so it is invalid, loop ignored, continued!")
# # Don't forget to update the number
# num+=1
# st=str(num)
# continue
for i in range(0,len(st)-2):
c_n=int(st[i])+int(st[i+1])+int(st[i+2])
if c_n>n:
chk=0
break
if chk==0:
pass
else:
# print("Valid st is",st)
ans_count+=1
# Now get the next m digit number
num+=1
st=str(num)
print(ans_count)
Comments
Post a Comment