What is wrong with my solution for code check problem CIELAB - c++

I am doing a code chef practice prblem https://www.codechef.com/problems/CIELAB in easy category. But my solution is not working. The submit screen is showing : Status wrong Answer
#include <iostream>
using namespace std;
int input ();
int difference (int, int);
int calculateWrongAns (int);
int main()
{
int num1;
int num2;
num1 = input();
num2 = input();
int actualAns = difference(num1, num2);
int res = calculateWrongAns(actualAns);
cout << res;
return 0;
}
int input () {
int x;
cin >> x;
return x;
}
int difference (int x, int y) {
if (x > y) {
return x - y;
} else if (x < y) {
return y - x;
} else {
return 0;
}
}
int calculateWrongAns (int actualAns) {
int lastNumber = actualAns % 10;
int otherNumbers = actualAns / 10;
int res;
if (otherNumbers != 0) {
res = (otherNumbers * 10) + (lastNumber == 1 ? 2 : lastNumber - 1);
} else {
res = lastNumber == 1 ? 2 : lastNumber - 1;
}
return res;
}
Thanks in advance.

The line
res = lastNumber == 1 ? 2 : lastNumber - 1;
is wrong. You are splitting the result in last digit and other digits. If the last digit is 1, you are changing it to 2. If it not 1, you are subtracting 1. That means, if the result is 30, you are subtracting 1. The new result is 29. Two digits differ. That's not correct. You could use
int calculateWrongAns (int actualAns) {
return (actualAns % 10) == 0 ? actualAns + 1 : actualAns - 1;
}

Related

How can I get the common digits of two int in C++? Example: (1234, 41567) --> 1 4

Given two int I want to get all the common digits and print out them separated by spaces.
So for example, if int x=1234; int y=41567; then I want to print out: 1 4.
This is my code. It does not work properly. When I run it, it prints 0 1 2 3 4 5 then stops.
I don't want to use vector nor arrays.
void problema3() {
int x, y, kX=0, kY=0;
cout << "x="; cin >> x;
cout << "y="; cin >> y;
int cx = x;
int cy = y;
for (int i = 0; i < 10; i++) {
kX = 0;
kY = 0;
x = cx;
y = cx;
while (x != 0 || kX==0) {
if (x % 10 == i) kX=1;
x /= 10;
}
while (y != 0 || kY == 0) {
if (y % 10 == i) kY=1;
y /= 10;
}
if (kX == 1 && kY == 1) cout << i << ' ';
}
}
int main()
{
problema3();
return 0;
}
If you're allowed to use std::set then you can do what you want as follows:
#include <iostream>
#include <set>
void print(int x, int y)
{
int individual_number1 = 0, individual_number2 = 0;
std::set<int> myset;
int savey = y;//this will be used to reset y when the 2nd do while loop finishes
do
{
individual_number1 = x % 10;
do
{
individual_number2 = y % 10;
if(individual_number1 == individual_number2)
{
myset.insert(individual_number1);
break;
}
y = y / 10;
}while( y > 0);
y = savey;
x = x / 10;
} while (x > 0);
//print out the element of the set
for(int i: myset)
{
std::cout<<i<<" ";
}
}
int main()
{
int x = 1234, y = 41567;
print(x, y);
return 0;
}
The output of the above program is as follows:
1 4
which can be seen here.
Your main bug is when assigning copies of cy.
//...
for (int i = 0; i < 10; i++) {
//...
x = cx;
y = cx; // <-- BUG! should read y = cy;
But that's not the only bug in your program.
Your digit detection logic is wrong. In particular, zero is not handled correctly, and since you did not put that reusable code in a function, your program is way more complex than it needs.
Here's the corrected logic for digit detection.
// checks if base 10 representation of a positive integer contains a certain digit (0-9)
bool hasDigit(int x, int d)
{
do
{
if (x % 10 == d)
return true;
x /= 10;
} while (x != 0);
return false;
}
Your main loop then becomes:
// assuming int x, y as inputs.
// ...
for (int i = 0; i < 10; ++i)
{
if (hasDigit(x, i) && hasDigit(y, i))
std::cout << i << ' ';
}
Which leaves very little room for bugs.
You can play with the code here: https://godbolt.org/z/5c5brEcEq

Why the last element in istringstream doesn't disappear in my code?

I am writing a calculator program in c++ , and I met two problems .
After I calculate 1 calculation questions , I only need to press enter ,then the program will output the last number in the previous calculation .
There are some incorrect answer , like " 7 / 9 / 10 * 1 * 4 / 6 - 3 * 9 - 8 - 7 " , the output should be -41.95 , but my answer is -11.95 .And I can't find what's wrong with my code.
The cin problem has been fixed when I use if(cin.get()!='\n')break;
And At the bottom there is a correct code of others .
my code use istringstream
#include<iostream>
#include<string>
#include<sstream>
#include<stack>
#include<iomanip>
using namespace std;
int priority(char op) {
if (op == '+' || op == '-') return 1;
else return 2;
}
double calculate(double x, double y, char c)
{
if (c == '+') return x + y;
if (c == '-') return x - y;
if (c == '*')return x * y;
return x / y;
}
int main() {
int n;
char op;
stack<double> nums;
stack<char> ops;
string a;
int count = 0;
while (getline(cin, a)) {
count++;
int allNum = 0;
int allzero = 0;
allNum++;
istringstream b(a);
b >> n;
if (n == 0) allzero++;
nums.push(n);
while (b >> op >> n) {
if (op == '\n') break;
allNum++;
if (n == 0) allzero++;
if (!ops.empty() && priority(op) <= priority(ops.top())) {
double y = nums.top();
nums.pop();
double x = nums.top();
nums.pop();
char tem = ops.top();
ops.pop();
double new_num = calculate(x, y, tem);
nums.push(new_num);
}
ops.push(op);
nums.push(n);
}
while (!ops.empty()) {
double y = nums.top();
nums.pop();
double x = nums.top();
nums.pop();
char tem = ops.top();
ops.pop();
double new_num = calculate(x, y, tem);
nums.push(new_num);
}
if (allzero != allNum) cout<< fixed << setprecision(2) << nums.top() << endl;
b.clear();
nums.pop();
}
}
this is the code I find on the internet
I learned the method from here , the biggest differentenss is that he use C ,and I use C++ .But his result is right .
#include <iostream>
#include <cstdio>
#include <cstring>
#include<stack>
using namespace std;
int P(char c)
{
if (c == '+' || c == '-') return 1;
return 2;
}
double Ans(double x, double y, char c)
{
if (c == '+') return x + y;
if (c == '-') return x - y;
if (c == '*')return x*y;
return x / y;
}
int main() {
int n;
while (scanf("%d",&n)!=EOF)
{
char c = getchar();
if (c=='\n'&&n == 0)break;
stack<char> op;
stack<double>num;
num.push(n);
while (true)
{
scanf("%c %d", &c, &n);
char k = getchar();
while (!op.empty()&&P(c)<=P(op.top()))
{
char t = op.top();
op.pop();
double y = num.top();
num.pop();
double x = num.top();
num.pop();
double ans = Ans(x, y, t);
num.push(ans);
}
op.push(c);
num.push(n);
if (k == '\n')break;
}
while (!op.empty())
{
char t = op.top();
op.pop();
double y = num.top();
num.pop();
double x = num.top();
num.pop();
double ans = Ans(x, y, t);
num.push(ans);
}
printf("%.2f\n", num.top());
}
return 0;
}

Reverse Integer Catch overflow C++

Hello I am trying a simple reverse integer operation in c++. Code below:
#include <iostream>
#include <algorithm>
#include <climits>
using namespace std;
class RevInteger {
public:
int reverse(int x)
{
int result = 0;
bool isNeg = x > 0 ? false : true;
x = abs(x);
while (x != 0)
{
result = result * 10 + x % 10;
x = x / 10;
}
if (isNeg)
result *= -1;
if (result > INT_MAX || result < INT_MIN)
return 0;
else
return (int)result;
}
};
When I give it an input as 1534236469; I want it to return me 0, instead it returns me some junk values. What is wrong in my program. Also, I am trying to use the climits lib for the purpose, is there a simpler way of doing the same?
The simplest approach is to use long long in place of int for the result, and check for overflow at the end:
long long result = 0;
/* the rest of your code */
return (int)result; // Now the cast is necessary; in your code you could do without it
Another approach is to convert the int to string, reverse it, and then use the standard library to try converting it back, and catch the problems along the way (demo):
int rev(int n) {
auto s = to_string(n);
reverse(s.begin(), s.end());
try {
return stoi(s);
} catch (...) {
return 0;
}
}
If you must stay within integers, an approach would be to check intermediate result before multiplying it by ten, and also checking for overflow after the addition:
while (x != 0) {
if (result > INT_MAX/10) {
return 0;
}
result = result * 10 + x % 10;
if (result < 0) {
return 0;
}
x = x / 10;
}
class Solution {
public:
int reverse(int x) {
int reversed = 0;
while (x != 0) {
if (reversed > INT_MAX / 10 || reversed < INT_MIN / 10) return 0;
reversed = reversed * 10 + (x % 10);
x /= 10;
}
return reversed;
}
};
If reversed bigger than 8 digit INT_MAX (INT_MAX / 10), then if we add 1 digit to reversed, we will have an int overflow. And similar to INT_MIN.
As suggested by #daskblinkenlight; changing the result as long long and type casting at the end solves the problem.
Working class:
class intReverse {
public:
int reverse(int x) {
long long result = 0; // only change here
bool isNeg = x > 0 ? false : true;
x = abs(x);
while (x != 0) {
result = result * 10 + x % 10;
x = x / 10;
}
if (isNeg) {
result *= -1;
}
if (result > INT_MAX || result < INT_MIN)
{
return 0;
}
else
{
return (int) result;
}
}
};
int reverse(int x) {
int pop = 0;
int ans = 0;
while(x) {
// pop
pop = x % 10;
x /= 10;
// check overflow
if(ans > INT_MAX/10 || ans == INT_MAX/10 && pop > 7) return 0;
if(ans < INT_MIN/10 || ans == INT_MIN/10 && pop < -8) return 0;
// push
ans = ans * 10 + pop;
}
return ans;
}

longest palindromic substring recursive solution

I am aware of solutions that uses the bottom up dynamic programing approach to solve this problem in O(n^2). I am specifically looking for a top down dp approach. Is it possible to achieve longest palindromic substring using a recursive solution?
Here is what I have tried but it fails for certain cases, but I feel I am almost on the right track.
#include <iostream>
#include <string>
using namespace std;
string S;
int dp[55][55];
int solve(int x,int y,int val)
{
if(x>y)return val;
int &ret = dp[x][y];
if(ret!=0){ret = val + ret;return ret;}
//cout<<"x: "<<x<<" y: "<<y<<" val: "<<val<<endl;
if(S[x] == S[y])
ret = solve(x+1,y-1,val+2 - (x==y));
else
ret = max(solve(x+1,y,0),solve(x,y-1,0));
return ret;
}
int main()
{
cin >> S;
memset(dp,0,sizeof(dp));
int num = solve(0,S.size()-1,0);
cout<<num<<endl;
}
For this case:
if(S[x] == S[y])
ret = solve(x+1,y-1,val+2 - (x==y));
it should be:
if(S[x] == S[y])
ret = max(solve(x + 1, y - 1, val + 2 - (x==y)), max(solve(x + 1, y, 0),solve(x, y - 1, 0)));
Because, in case you cannot create a substring from x to y, you need to cover the other two cases.
Another bug:
if(ret!=0){ret = val + ret;return ret;}
you should return ret + val and not modify ret in this case.
The main problem is you store the final val into dp[x][y], but this is not correct.
Example:
acabc , for x = 1 and y = 1, val = 3, so dp[1][1] = 3, but actually, it should be 1.
Fix:
int solve(int x,int y)
{
if(x>y)return 0;
int &ret = dp[x][y];
if(ret!=0){return ret;}
if(S[x] == S[y]){
ret = max(max(solve(x + 1, y),solve(x, y - 1)));
int val = solve(x + 1, y - 1);
if(val >= (y - 1) - (x + 1) + 1)
ret = 2 - (x == y) + val;
}else
ret = max(solve(x+1,y),solve(x,y-1));
return ret;
}
Longest Palindrome using Recursion in Javascript:
const longestPalindrome = str => {
if (str.length > 1){
let [palindrome1, palindrome2] = [str, str];
for (let i=0;i<Math.floor(str.length/2);i++) {
if(str[i]!==str[str.length-i-1]) {
palindrome1 = longestPalindrome(str.slice(0, str.length-1));
palindrome2 = longestPalindrome(str.slice(1, str.length));
break;
}
}
return palindrome2.length > palindrome1.length ? palindrome2 : palindrome1;
} else {
return str;
}
}
console.log(longestPalindrome("babababababababababababa"));
here is the python solution for this:
class Solution:
def longestPalindrome(self, s: str) -> str:
memo = {}
def isPalindrome(left,right):
state = (left, right)
if state in memo: return memo[state]
if left >= right:
memo[state] = True
return True
if s[left] != s[right]:
memo[state] = False
return False
memo[state] = isPalindrome(left+1, right-1)
return memo[state]
N = len(s)
result = ""
for i in range(N):
for j in range(i,N):
if (j-i+1) > len(result) and isPalindrome(i,j):
result = s[i:j+1]
return result
/*C++ program to print the largest palindromic string present int the given string
eg. "babad" contains "bab" and "aba" as two largest substring.
by occurance, "bab" comes first hence print "bab".
*/
#include<bits/stdc++.h>
using namespace std;
bool ispalindrome(string s)
{
int l = s.length()-1;
int r = 0;
while(l>r){
if(s[l]!=s[r])
return false;
l--;r++;
}
return true;
}
int main()
{
string str,str1,str3;
vector<string> str2;
cin>>str;
int len = str.length();
for(int i=0;i<len;i++)
{
for(int j=i;j<=len;j++)
{
str1 = "";
str1.append(str,i,j);
if(ispalindrome(str1)){
str2.push_back(str1);
}
}
}
int max = 0;
for(int i=0;i<str2.size();i++)
{
if(str2[i].length()>max){
max = str2[i].length();
str3 = str2[i];
}
}
cout<<"MAXIMUM LENGTH IS : "<<max<<"\nLARGEST PALINDROMIC STRING IS : "<<str3<<endl;
return 0;
}
#include <iostream>
using namespace std;
int ans=0;
bool fn(string &s,int i,int j){
if(i==j)
return 1;
if((j-i)==1&&s[i]==s[j])
return 1;
else if((j-i)==1&&s[i]!=s[j])
return 0;
if(s[i]==s[j]){
if(fn(s,i+1,j-1)){
ans=max(ans,j-i+1);
return 1;
}
else{
return 0;
}
}
else{
fn(s,i,j-1);
fn(s,i+1,j);
return 0;
}
}
int main() {
string s;
cin>>s;
int last=s.length()-1;
fn(s,0,last);
cout<<ans<<endl;
return 0;
}

Function returns result lesser by 1 than it should be

I'm trying to write an octal to decimal conversion app.
The problem is the return value is 1 less than it should be, ex.:
INPUT: 2426 (OCT)
SHOULD RETURN: 1302 (DEC)
RETURNS: 1301 (DEC)
Any ideas what's wrong? I'm using newest Code::Blocks if someone wants to know.
Here's my code:
int oct2dec (int number) {
int system = 8;
int length = IntegerLength(number);
int power = length - 1;
int result = 0;
int partial = 0;
do {
partial = part_nr(number);
cout<<"czastka: "<<partial<<endl;
result = result + (partial * pow(system,power));
number = number - (partial * pow(10,power));
power--;
} while (number>0);
return result;
}
part_nr function:
int part_nr(int number) {
int multipler = 1;
int result = 0;
do {
int temp=number/multipler;
if(temp<10) result = temp;
multipler = multipler*10;
} while (result == 0);
return result;
}
IntegerLength function:
int IntegerLength(int value) {
int divisor = 10;
int length = 1;
while(value >= divisor)
{
value = (value - (value % divisor)) / divisor;
length ++;
}
return length;
}
(btw. I've translated variables from my native lang to english, so if you see any non-eng variable say so, i'll correct it)
I'd think you just have problems with rounding in you algorithm. Anyway, this is not the way to do the conversion anyway: on the way in, you just read the digit and add it to the current value. If there is another digit, you multiply by 8 and reapeat.
On the way out, you take the remainder (modulus) of the division by 10 to form the next digit. Then you divide by 10 and while the result is non-zero you repeat.
You can do this much easier than what you are trying to. For example:
unsigned int oct2dec(unsigned int oct) {
int dec = 0, m = 1;
while (oct > 0) {
dec += m * (oct % 10);
oct /= 10;
m *= 8;
}
return dec;
}
I have tested your code and it is outputting the value you claim to be expected. The only problem I encountered was with rounding. I changed the pow() function call to powf(), and then I cast the result of that function to integer.
This is the code I tested (VS2010 C++ Project):
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
int part_nr(int number) {
int multipler = 1;
int result = 0;
do {
int temp=number/multipler;
if(temp<10) result = temp;
multipler = multipler*10;
} while (result == 0);
return result;
}
int IntegerLength(int value) {
int divisor = 10;
int length = 1;
while(value >= divisor)
{
value = (value - (value % divisor)) / divisor;
length++;
}
return length;
}
int oct2dec (int number) {
int system = 8;
int length = IntegerLength(number);
int power = length - 1;
int result = 0;
int partial = 0;
do {
partial = part_nr(number);
cout<<"czastka: "<<partial<< endl;
result = result + (partial * (int)powf(system,power));
number = number - (partial * (int)powf(10,power));
power--;
} while (number>0);
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
int res = oct2dec(2426);
cout << "res is " << res << endl;
getchar();
return 0;
}