CodeSignal isLucky task c++ - c++

Started to practice C++ by trying to do some tasks in CodeSignal, but I can’t figure it out why it has an output which is always false. Saw a similar answer to this task but didn’t want to copy and paste without understanding where the error is.
Ticket numbers usually consist of an even number of digits. A ticket number is considered lucky if the sum of the first half of the digits is equal to the sum of the second half.
Example:
For n = 1230, the output should be isLucky(n) = true
For n = 239017, the output should be isLucky(n) = false
Code:
bool isLucky(int n) {
string convert = to_string(n); // to convert from string to int
int sizehalbe = convert.size() / 2; //divide into 2 halfs
//Stor each half
string h1 = convert.substr(0, sizehalbe-1);
string h2 = convert.substr(sizehalbe, convert.size()-1);
int sum1=0, sum2=0; //Calculate the halfs
for(int i=0;i<h1.length();i++)
{
sum1 += int(h1.at(i));
}
for(int j=0;j<h2.length();j++)
{
sum2 += int(h2.at(j));
}
if(sum1 == sum2)
return true;
else
return false;
}

(1). Foremost your h1 always miss one digit so instead of
h1 = convert.substr(0, sizehalbe-1);
that's the only main issue your code has, convert should be gone till sizehalbe
string h1 = convert.substr(0, sizehalbe);
(2). whenever you typecast from character to integer, check what it gives
cout<<int('0'); will give you 48 instead of 0.
in particular, this case it's not changed your main output
(due to both sum1 & sum2 will get higher result than what actually should be,
but get same level of higher.)
sum½ += int(h½.at(i)) - 48;
(3). you can optimize your last condition.
when boolean result is depending on condition you can do
return (sum1 == sum2);

Related

Problem with Reversing Large Integers On Leetcode?

I was working on this problem from Leetcode where it has this requirement of reversing numbers whilst staying within the +/-2^31 range. I checked out other solutions made for this problem, and from there created my own solution to it. It worked successfully for numbers ranging from 10 to less than 99,999,999. Going more than that(when trying to submit the code to move to the next question) would throw an error saying:
"Line 17: Char 23: runtime error: signed integer overflow: 445600005 * 10 cannot be represented in type 'int' (solution.cpp)"
This was the input given when trying to submit the code: 1534236469
My code
class Solution {
public:
int reverse(int x) {
int flag = 0;
int rev = 0;
if (x >= pow(2, 31)) {
return 0;
} else {
if (x < 0) {
flag = 1;
x = abs(x);
}
while(x > 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if (flag == 1) {
rev = rev*(-1);
}
return rev;
}
}
};
As you can see from my code, I added an if statement that would basically return 0 if the number was greater than 2^31. Unfortunately, this was wrong.
Can anyone explain how this can be fixed? Thank you in advance.
Problem statement asks to return 0 if reversed number does not belong to integer range :
If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
In your code you checked if input fits in integer range but their arises a corner case when the integer has 10 digits and last digit is >2 (and for some cases 2).
Lets consider the input 1534236469: 1534236469 < 2^31 - 1
so program executes as expected now lets trace last few steps of program execution : rev = 964632435 and x = 1 problem arises when following statement is executed :
rev = rev * 10 + x % 10;
Now, even though input can be represented as integer rev * 10 i.e. 9646324350 is greater than integer range and correct value that should be returned is zero
Fix ?
1. Lets consider 10 digit case independently
Even though this can be done, it gives rise to unnecessary complications when last digit is 2
2. Make rev a long integer
This works perfectly and is also accepted, but sadly this is not expected when solving this problem as statement explicitly asks to not use 64-bit integers
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
3. Checking before multyplying by 10 ?
This works as expected. Before multyplying rev by 10 check if it is >= (pow(2,31)/10)
while(x > 0) {
if (rev >= pow(2, 31)/10 )
return 0;
rev = rev * 10 + x % 10;
x /= 10;
}
I hope this solves your doubt !! Comment if you find something wrong as this is my first answer.
Note : The following if statement is unnecessary as input is always a 32-bit integer
Given a signed 32-bit integer x
if (x >= pow(2, 31)) {
return 0;
}
Edit : As most of the comments pointed it out, instead of pow(2,31), use INT_MAX macro as it suffices here.
public static int reverse(int x) {
boolean isNegative = false;
if (x < 0) {
isNegative = true;
x = -x;
}
long reverse = 0;
while (x > 0) {
reverse = reverse * 10 + x % 10;
x=x/10;
}
if (reverse > Integer.MAX_VALUE) {
return 0;
}
return (int) (isNegative ? -reverse : reverse);
}

if statement inside of for loop not being executed

Writing a program to solve problem four of project euler: Find the largest palindrome made from the product of two 2-digit numbers. Heres my reprex:
#include <iostream>
int reverseNumber(int testNum)
{
int reversedNum, remainder = 0;
int temp = testNum;
while(temp != 0)
{
remainder = temp % 10;
reversedNum = reversedNum * 10 + remainder;
temp /= 10;
}
return reversedNum;
}
int main()
{
const int MIN = 100;
int numOne = 99;
int product = 0;
for(int numTwo = 10; numTwo < 100; numTwo++)
{
product = numOne * numTwo;
if (reverseNumber(product) == product)
{
int solution = product;
std::cout << solution << '\n';
return 0;
}
}
return 0;
}
My main thought process behind this is that the for loop will go through every number from 10 to 99 and multiply it by 99. My intended outcome is for it to print 9009 which is the largest palindrome with 2 factors of 2 digits. So what I think should happen here is the for loop will go from 10 to 99, and each loop it should go through the parameters of the if statement which reverses the number and sees if it equals itself.
I've made sure it wasn't a compiler issue, as this is recurring between different compilers. The reverseNumber() function returns the proper number every time I've tested it, so that shouldn't be the problem, however this problem only occurs when the function is involved in the logical comparison. By this I mean if that even I set it equal to a variable and put the variable in the if parameters, the issue still occurs. I'm pretty much stumped. I just hope it's not some silly mistake as I've been on this for a couple days now.
int reversedNum, remainder = 0;
You should be aware that this gives you (in an automatic variable context) a zero remainder but an arbitrary reversedNum. This is actually one of the reasons some development shops have the "one variable per declaration" rule.
In other words, it should probably be:
int reversedNum = 0, remainder;
or even:
int reversedNum = 0;
int remainder;
One other thing that often helps out is to limit the scope of variable to as small an area as possible, only bringing them into existence when needed. An example of that would be:
int reverseNumber(int testNum) {
int reversedNum = 0;
while (testNum != 0) {
int remainder = testNum % 10;
reversedNum = reversedNum * 10 + remainder;
testNum /= 10;
}
return reversedNum;
}
In fact, I'd probably go further and eliminate remainder altogether since you only use it once:
reversedNum = reversedNum * 10 + testNum % 10;
You'll notice I've gotten rid of temp there as well. There's little to gain by putting testNum into a temporary variable since it's already a copy of the original (as it was passed in by value).
And one other note, more to do with the problem rather than the code. You seem to be assuming that there is a palindrome formed that is a multiple of 99. That may be the case but a cautious programmer wouldn't rely on it - if you're allowed to assume things like that, you could just replace your entire program with:
print 9009
Hence you should probably check all possibilities.
You also get the first one you find which is not necessarily the highest one (for example, let's assume that 99 * 17 and 99 * 29 are both palindromic - you don't want the first one.
And, since you're checking all possibilities, you probably don't want to stop at the first one, even if the nested loops are decrementing instead of incrementing. That's because, if 99 * 3 and 97 * 97 are both palindromic, you want the highest, not the first.
So a better approach may be to start high and do an exhaustive search, while also ensuring you ignore the palindrome check of candidates that are smaller that your current maximum, something like (pseudo-code)
# Current highest palindrome.
high = -1
# Check in reverse order, to quickly get a relatively high one.
for num1 in 99 .. 0 inclusive:
# Only need to check num2 values <= num1: if there was a
# better palindrome at (num2 * num1), we would have
# already found in with (num1 * num2).
for num2 in num1 .. 0 inclusive:
mult = num1 * num2
# Don't waste time doing palindrome check if it's
# not greater than current maximum - we can't use
# it then anyway. Also, if we find one, it's the
# highest possible for THIS num1 value (since num2
# is decreasing), so we can exit the num2 loop
# right away.
if mult > high:
if mult == reversed(mult):
high = mult
break
if high >= 0:
print "Solution is ", high
else:
print "No solution"
In addition to properly initializing your variables, if you want the largest palindrome, you should switch the direction of your for loop -- like:
for(int numTwo = 100; numTwo > 10; numTwo--) {
...
}
or else you are just printing the first palindrome within your specified range

Why does the following program gives wrong answer when I remove "+ mod" from statement check . Problem link: https://www.codechef.com/problems/FFC219B

The statement check is where I don't understand why it shows wrong answer on submission when I write "sum = (solution[R]-solution[L-1])%mod;" instead. Here I have not added mod within the bracket. I don't see how the answer changes by adding a value of taking the mod of same. Problem code in codechef: https://www.codechef.com/problems/FFC219B
#include<iostream>
#define ll long long
#define mod 1000000007 //the modulus we need to take for the final answer
#define endl "\n"
using namespace std;
long long solution[100007] = {0}; //Initialising all the values with zero
int main(){
ios_base :: sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
solution[0] = 0;
ll a1=1,a2=2,a3=3,a4=4; //The variable initialising as per the problem
for(int i = 1;i <= 100007;i++){
ll k=(a1 * a2) % mod * a3 % mod * a4 % mod;
solution[i] = (solution[i-1]+k)%mod; //Adding the previous values as we are to find the sum in range
a1++;
a2++;
a3++;
a4++;
}
int t; //Taking input for number of test cases
cin>>t;
while(t-->0)
{
int L,R;
cin>>L>>R; //Taking the range input
long long sum = 0;
sum = (solution[R]-solution[L-1] + mod)%mod; //statement check & final answer
cout<<sum<<endl;
}
return 0;
}
The program can give the incorrect answer since the correct answer must always be a positive - not a negative - number.
When you subtract consecutive modulo values, the result may well be negative even though the numbers themselves are increasing (eg, (4^3)%10 - (4^2)%10 = 64%10 - 16%10 = 4-6 = -2), . This means “solution[R]-solution[L-1]” may also well be negative, which means “(solution[R]-solution[L-1]) % mod” will also be negative - although clearly the answer (the number of people affected) must always be positive.
So adding the mod value in this fashion ensures that the result will always be positive.

Recursive Binary Conversion C++

I am fairly new to C++. I am trying to write a recursive binary function. The binary output needs to be 4 bits, hence the logic around 15 and the binary string length. It converts to binary correctly, the problem I am having is ending the recursive call and returning the binary string to the main function. It seems to just backwards through the call stack? Can someone help me understand what is going on?
Assuming using namespace std. I know this is not good practice, however it is required for my course.
string binary(int number, string b){
if (number > 0 && number < 15){
int temp;
temp = number % 2;
b = to_string(temp) + b;
number = number / 2;
binary(number, b);
}
else if (number > 15){
b = "1111";
number = number - 15;
binary(number, b);
}
else if (number == 15){
b = "11110000";
return b;
}
//should be if number < 1
else{
int s = b.size();
//check to make sure the binary string is 4 bits or more
if (s >= 4){
return b;
}
else{
for (int i = s; i < 4; i++){
b = '0' + b;
}
return b;
}
}
}
You have your function returning a string, but then you require the user to supply an initialized string for you, and you throw away the return value except for the base cases of 15 and 0. The rest of the time, your actual communication is using the parameter b. This multiple communication will cause some headaches.
I also note that you return a properly padded 4-bit number in normal cases; however, you force a return an 8-bit 15 for the exact value 15. Is this part of the assignment specification?
The logic for larger numbers is weird: if the amount is more than 15, you return "1111" appended to the representation for the remainder. For instance, 20 would return as binary(5) followed by "1111", or "1011111", which is decidedly wrong. Even stranger, it appears that any multiple of 15 will return "11110000", since that clause (== 15) overwrites any prior value of b.
I suggest that you analyze and simplify the logic. There should be two cases:
(BASE) If number == 0, return '0'
(RECUR) return ['1' (for odd) else '0'] + binary(number / 2)
You also need a top-level wrapper that checks the string length, padding out to 4 digits if needed. If the "wrapper" logic doesn't fit your design ideas, then drop it, and work only with the b parameter ... but then quit returning values in your other branches, since you don't use them.
Does this get you moving?

Why does trunc(1) output as 0?

Can someone explain me why in c++ happens such a thing:
double tmp;
... // I do some operations with tmp
// after which it has to be equal to one
cout << tmp; // prints 1
cout << trunc(tmp); // prints 0
cout << trunc(tmp*10); // prints 9
I am using this for separation part right of decimal part from the number for example if i have: 5.010 ... i want to have 0.010 .. so I am using:
double remainder = tmp - trunc(tmp);
I am posting the whole code....the suggestion with floor does not worked
short getPrecision(double num, short maxPrecision) {
// Retrieve only part right of decimal point
double tmp = fabs(num - trunc(num));
double remainder = tmp;
// Count number of decimal places
int c = 0;
while (remainder > 0 && c < maxPrecision) {
tmp *= 10;
remainder = tmp - trunc(tmp);
c++;
}
return c;
}
When I run this function for example with 5.1 the remanider is 0 instead of 1
After some calculations it has to be one? Well, it could as well be 0.99999999999999999. Floating point operations are not precise, you should always take that into account.
Please see picture at http://en.cppreference.com/w/cpp/numeric/math/trunc. The chart there explains the inconsistency with truncing 1. Probably the same applies to 10 as well
This should help you achieving what you need:
double remainder = tmp - floor(tmp);