For a positive integer M, let ππππππππ(πΌ) be the sum of digits of the number M (when written in decimal).
For example, ππππππππ(π·πΆπΈπΉ)=1+0+2+3=6.
Given a positive integer N, find the smallest integer X greater than N such that
ππππππππ(π½) and ππππππππ(π) have different parity, i.e. one of them is odd and the other is even
EXPLANATION:
Let I be the given integer, S be the digit sum, x be the last digit.
Case 1:S+1 has different parity as S Ans:(I+1)
Case 2:S+1 has same parity as S \implies x = 9 \implies x+1 = 10 \therefore x for S+1 will be 0 and previous digits would be affected \implies x+1 = 1 \therefore x for S+2 will be 1 and previous digits wonβt be affected \implies S+2 will have different parity than S+1 and hence, S Ans:(I+2)
TIME COMPLEXITY:
The above computation can be done in constant time. Hence, the solution has a time complexity of O(1).
It works on test cases. But shows wrong on submit. Can anyone help me find the error?
#include<iostream>
using namespace std;
int main() {
// your code goes here
int l;
cin>>l;
int n, s;
while(l--){
s=0;
cin>>n;
int x=n;
while(s%2==0){
x=n;
while(x>0){
s+=x%10;
x/=10;
}
n++;
}
cout<<--n<<endl;
}
return 0;
}
Congrats on posting your first query!
Your logic is correct but the implementation is not correct. I have made some changes to your code based on your logic, please go through it.
#include<iostream>
using namespace std;
int digitSum(int n){
int sum=0;
while(n>0){
sum+=n%10;
n=n/10;
}
return sum;
}
int main() {
// your code goes here
int l;
cin>>l;
int n, s;
while(l--){
cin>>n;
int x=n;
while(digitSum(n)%2==digitSum(x)%2){// increase the number x until the parity of digitSum of n is not same as parity of digitSum of x
x++;
}
cout<<x<<endl;
}
return 0;
}
Please reply if you find any difficulty understanding the code.
Thanks
Hey @mannshah1211 , @kuldeep_singh ,
your code is giving WA on Test case
1
199
your code is printing 201 (digitsum(199) = 19(odd) and digitsum(201) = 3(odd)).but I should have different parity.