We were given an assignment to make a program that takes two decimal numbers as input and performs binary addition in the background then outputs a decimal sum. I seem to be getting the wrong results despite how much I think my code logic is correct.
My current sum gives me 0. The Correct answer should be 24.
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int add(int, int);
int decbin(int);
int bindec(long);
int binADD(string, string);
int main()
{
int a = 15;
int b = 9;
int z;
z = add(a,b);
cout << z;
return 0;
}
int add(int a, int b)
{
int z;
ostringstream x, y;
x << decbin(a);
y << decbin(b);
z = binADD(x.str(), y.str());
return z;
}
int decbin(int x)
{
int d[16];
int i = 0;
int j;
int ans;
while(x > 0)
{
d[i] = x % 2;
i++;
x = x / 2;
}
for(j = i - 1; j >= 0; j--)
{
ans = d[j];
}
return ans;
}
int bindec(int x)
{
int bin, dec = 0, rem, base = 1;
bin = x;
while (x > 0)
{
rem = x % 10;
dec = dec + rem * base;
base = base * 2;
x = x / 10;
}
return dec;
}
int binADD(string a, string b)
{
int carry = 0;
int result[5];
int res;
int ans;
for(int i = 0; i < 4; i++)
{
if(a[i] == '1' && b[i] == '1' && carry == 0)
{
result[i] = 0;
carry = 1;
}
else if(a[i] == '0' && b[i] == '1' && carry == 1)
{
result[i] = 0;
carry = 1;
}
else if(a[i] == '1' && b[i] == '1' && carry == 1)
{
result[i] = 1;
carry = 1;
}
else if(a[i] == '1' && b[i] == '0' && carry == 1)
{
result[i] = 0;
carry = 1;
}
else if(a[i] == '1' && b[i] == '0' && carry == 0)
{
result[i] = 1;
carry = 0;
}
else if(a[i] == '0' && b[i] == '0' && carry == 1)
{
result[i] = 1;
carry = 0;
}
else if(a[i] == '0' && b[i] == '1' && carry == 0)
{
result[i] = 1;
carry = 0;
}
else if(a[i] == '0' && b[i] == '0' && carry == 0)
{
result[i] = 0;
carry = 0;
}
}
result[4] = carry;
for(int j = 4; j >= 0; j--)
{
res = result[j];
}
ans = bindec(res);
return ans;
}
Related
I'm trying to solve this question. My solution is almost identical to the fastest one. But for a test case, I have time limit exceeded while the other (the fastest one) does not. Could anybody explain for me why my code is so slow?. Here is my code:
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int M = grid.size();
if(M == 0) return 0;
int N = grid[0].size();
if(N == 0) return 0;
int flag = 2;
int count = 0;
for(int i = 0; i < M; ++i){
for(int j = 0; j < N; ++j){
if(grid[i][j] == '1'){
//breadth-first search from here
flag++;
count++;
queue<pair<int, int>> nodes;
grid[i][j] = flag;
nodes.push({i,j});
while(!nodes.empty()){
auto node = nodes.front();
nodes.pop();
if(node.first > 0 && grid[node.first-1][node.second] == '1'){
grid[node.first-1][node.second] = flag;
nodes.push(make_pair(node.first-1, node.second));
}
if(node.first < M-1 && grid[node.first+1][node.second] == '1'){
grid[node.first+1][node.second] = flag;
nodes.push(make_pair(node.first+1, node.second));
}
if(node.second > 0 && grid[node.first][node.second-1] == '1'){
grid[node.first][node.second-1] = flag;
nodes.push(make_pair(node.first, node.second-1));
}
if(node.second < N-1 && grid[node.first][node.second + 1] == '1'){
grid[node.first][node.second+1] = flag;
nodes.push(make_pair(node.first, node.second+1));
}
}
}
}
}
return count;
}
};
Here is the fastest solution. The author was very clever to use the array offsets, and I think that's the only difference between his code and mine. But I don't think it speed up the code.
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0, offsets[] = {0, 1, 0, -1, 0};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
islands++;
grid[i][j] = '0';
queue<pair<int, int>> todo;
todo.push({i, j});
while (!todo.empty()) {
pair<int, int> p = todo.front();
todo.pop();
for (int k = 0; k < 4; k++) {
int r = p.first + offsets[k], c = p.second + offsets[k + 1];
if (r >= 0 && r < m && c >= 0 && c < n && grid[r][c] == '1') {
grid[r][c] = '0';
todo.push({r, c});
}
}
}
}
}
}
return islands;
}
};
The problem here is that you are overwriting the islands on grid with the value of flag. When the value of flag gets equal to '1', then your code enters an infinite cycle because you are asking for cell with '1' for detecting islands.
With this extra line change on your code I got accepted on the problem.
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int M = grid.size();
if(M == 0) return 0;
int N = grid[0].size();
if(N == 0) return 0;
int flag = 2;
int count = 0;
for(int i = 0; i < M; ++i){
for(int j = 0; j < N; ++j){
if(grid[i][j] == '1'){
//breadth-first search from here
flag++;
if (flag == '1') flag++; /////THIS LINE HERE
count++;
queue<pair<int, int>> nodes;
grid[i][j] = flag;
nodes.push({i,j});
while(!nodes.empty()){
auto node = nodes.front();
nodes.pop();
if(node.first > 0 && grid[node.first-1][node.second] == '1'){
grid[node.first-1][node.second] = flag;
nodes.push(make_pair(node.first-1, node.second));
}
if(node.first < M-1 && grid[node.first+1][node.second] == '1'){
grid[node.first+1][node.second] = flag;
nodes.push(make_pair(node.first+1, node.second));
}
if(node.second > 0 && grid[node.first][node.second-1] == '1'){
grid[node.first][node.second-1] = flag;
nodes.push(make_pair(node.first, node.second-1));
}
if(node.second < N-1 && grid[node.first][node.second + 1] == '1'){
grid[node.first][node.second+1] = flag;
nodes.push(make_pair(node.first, node.second+1));
}
}
}
}
}
return count;
}
};
Note: This code was only for ilustrate the error, that doesn't mean that is an elegant solution for the bug.
This question already has answers here:
How to append a char to a std::string?
(14 answers)
Closed 3 years ago.
So, I've been writing a program that adds two Roman numbers and outputs the sum in Roman numbers as well. The issue I ran was and is, that the thing that checks the result is only reading the first output letter, not the entire output.
Which made me think about how to fill the string with chars (or strings with a length of one). I do something like:
#include <iostream>
int main() {
std::string str{" "};
for (int i = 0; i < 5; ++i) {
str[i] = 'A';
}
std::cout << str;
}
After running this, you get output "A", when I want it to be "AAAAA". I just really don't know how to make a list of chars dynamic one, if to say technical.
For context, here is the code for the Roman numerals. I tried doing this in Python, but it didn't work out well too, and since I initially started in C++, I want to know how to do such an operation there.
#include <iostream>
using namespace std;
// simple shit
// a func str gets a sum, then with while loops 'fills' the " " in the string s with some letters
string str(int sum) {
string s = " ";
int i = 0;
while (sum >= 1000) {
s[i] = 'M';
sum -= 1000;
++i;
}
while (sum >= 500) {
s[i] = 'D';
sum -= 500;
++i;
}
while (sum >= 100) {
s[i] = 'C';
sum -= 100;
++i;
}
while (sum >= 50) {
s[i] = 'L';
sum -= 50;
++i;
}
if (sum == 19) {
s[i] = 'X';
++i;
s[i] = 'I';
++i;
s[i] = 'X';
++i;
sum -= 19;
}
while (sum >= 10) {
s[i] = 'X';
++i;
}
if (sum == 19) {
s[i] = 'X';
++i;
s[i] = 'I';
++i;
s[i] = 'X';
++i;
sum -= 19;
}
if (sum == 9) {
s[i] = 'I';
++i;
s[i] = 'X';
++i;
sum -= 9;
}
while (sum >= 5) {
s[i] = 'V';
++i;
}
if (sum == 4) {
s[i] = 'I';
++i;
s[i] = 'V';
++i;
sum -= 4;
}
while (sum >= 1) {
s[i] = 'I';
++i;
}
for (int i = 0; i < s.length(); ++i) {
if (s[i] == ' ') {
s[i] = '\0';
}
}
//..and returns the string, full of " ", when I don't need those
return s;
}
//uh, that's the func to check if IX == 19, not 21. don't care about this one
int a(string prev) {
if (prev == "M") {
return 1000;
}
if (prev == "D") {
return 500;
}
if (prev == "C") {
return 100;
}
if (prev == "L") {
return 50;
}
if (prev == "X") {
return 10;
}
if (prev == "V") {
return 5;
}
if (prev == "I") {
return 1;
}
else {
return 0;
}
}
int main() {
//all the strings and other cool stuff
string s, letter, prev;
cin >> s;
int sum;
int prev_check;
int l = s.length();
// a loop to find a letter in a string we just input, and 'parse' it to the normal-digits (arabic) form
for (int i = 0; i < l; i++) {
letter = s[i];
if (letter == "M") {
sum += 1000;
//checking if nothing less than current Rome digit is behind it
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 1000) {
sum -= prev_check * 2;
//you may be wondering, why times two?
//because I've already added the letter behind to my sum,
//so I have to substract it from sum twice
}
}
}
// fun fact - there cant exist numbers such as IM (999) in Rome letter, only C, X and V are "substractable"
//yet, I've still added this kinda "substraction" to all letters, just because I'm lazy to input specific ones for debugging my "substraction" func
if (letter == "D") {
sum += 500;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 500) {
sum -= prev_check * 2;
}
}
}
if (letter == "C") {
sum += 100;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 100) {
sum -= prev_check * 2;
}
}
}
if (letter == "L") {
sum += 50;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 50) {
sum -= prev_check * 2;
}
}
}
if (letter == "X") {
sum += 10;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 10) {
sum -= prev_check * 2;
}
}
}
if (letter == "V") {
sum += 5;
if (i > 0) {
prev = s[i - 1];
prev_check = a(prev);
if (prev_check < 5) {
sum -= prev_check * 2;
}
}
}
if (letter == "I") {
sum += 1;
}
}
//and... out
cout << str(sum);
}
It's quite some code, I know, I added a few comments explaining what am I doing here and there.
The below code might help to output 5 'A'
#include <iostream>
#include <vector>
int main() {
std::vector<char> val;
for (int i = 0; i < 5; ++i) {
val.push_back('A');
}
for (int a = 0; a < val.size(); ++a)
{
std::cout << val[a];
}
}
here is a loop that is supposed to add prime numbers only and ignore non prime numbers but it is not working properly ,my skills are pretty basic , so please try to simplify your answers as much as possible,
#include <iostream>
using namespace std;
int main()
{
int n = 0, a = 0, sum = 0;
cin >> n;
for (int j = 1; j <= n; j++)
{
cin >> a;
if (a == 1)
{
continue;
}
if (a == 2 || a == 3)
{
sum += a;
}
if (a % 2 == 0)
{
continue;
}
for (int i = 3; i < a; i++)
{
if (a % i != 0)
{
sum += a;
}
else
{
continue;
}
}
}
cout << sum;
return 0;
}
I would prefer using this function instead. You should add cmath library:
bool isPrime(int number) {
if (number <= 1)
return false;
for (int i = 2; i <= sqrt(number); i++)
{
if (number % i == 0)
{
return false;
}
}
return true;
}
But if you want to continue with your code, after checking a == 2 || a == 3 you should continue. And last part before for loop you should define some boolean like bool isPrime = true. Then if its finds a divider you should assing it to false and break.
Your full code should be something like this:
#include <iostream>
using namespace std;
int main()
{
int n = 0, a = 0, sum = 0;
cin >> n;
for (int j = 1; j <= n; j++)
{
cin >> a;
if (a == 1)
{
continue;
}
if (a == 2 || a == 3)
{
sum += a;
continue;
}
if (a % 2 == 0)
{
continue;
}
bool isPrime = true;
for (int i = 3; i < a; i++)
{
if (a % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime) {
sum += a;
}
}
cout << sum;
return 0;
}
Problem:
"maxPrint" resets to 0 out of nowhere.
In function "skaitymas" it complies to if, and changes itself to "p" finding the biggest one.
After the function is done, "maxPrint" suddenly becomes 0 again...
maxPrint is not even used anywhere after that..
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
const char duomF[] = "1.txt";
const char rezF[] = "rez1.txt";
const int CMax = 81;
void reset(int SK[])
{
for (int i = 0; i < CMax; i++)
{
SK[i] = 0;
}
}
void skaitymas(int SK[], int &n, int &maxPrint)
{
ifstream df(duomF);
char temp;
int tempsk;
int p;
df >> n;
for (int i = 0; i < n; i++)
{
df >> p;
if (p > maxPrint)
{
maxPrint = p;
}
cout << p << " " << maxPrint << endl;
for (int j = CMax - p; j < CMax; j++)
{
df >> temp;
{ if (temp == '0') tempsk = 0;
else if (temp == '1') tempsk = 1;
else if (temp == '2') tempsk = 2;
else if (temp == '3') tempsk = 3;
else if (temp == '4') tempsk = 4;
else if (temp == '5') tempsk = 5;
else if (temp == '6') tempsk = 6;
else if (temp == '7') tempsk = 7;
else if (temp == '8') tempsk = 8;
else if (temp == '9') tempsk = 9;
}
SK[j] += tempsk;
}
}
df.close();
}
void skaiciavimas(int SK[])
{
int temp;
for (int i = CMax; i >= 0; i--)
{
if(SK[i] >= 10)
{
temp = SK[i] / 10;
SK[i-1] += temp;
SK[i] = SK[i] % 10;
}
}
}
int main()
{
int SK[CMax];
int n; int maxPrint = 0;
reset(SK);
skaitymas(SK, n, maxPrint);
skaiciavimas(SK);
for (int i = CMax - (maxPrint - 1); i < CMax; i++) cout << SK[i] << " ";
cout << maxPrint << endl;
ofstream rf(rezF);
for (int i = CMax - (maxPrint - 1); i < CMax; i++) rf << SK[i];
rf.close();
return 0;
}
In this loop you are accessing SK out of bounds:
void skaiciavimas(int SK[])
{
int temp;
for (int i = CMax; i >= 0; i--)
{
if(SK[i] >= 10) //<<< BUG (i = CMax)
{
temp = SK[i] / 10; //<<< BUG (i = CMax)
SK[i-1] += temp; //<<< BUG (i = 0)
SK[i] = SK[i] % 10; //<<< BUG (i = CMax)
}
}
}
Note that valid indices for SK are from 0 to CMax - 1, so accessing SK[CMax] results in undefined behaviour, as does accessing SK[-1].
Note that when you write to an array out of bounds you may well overwrite adjacent variables, which probably explains the unexpected modification of maxPrint, but as with any case of undefined behaviour, literally anything can happen.
Without knowing what your code is supposed be doing I can only guess that perhaps your for loop should be:
for (int i = CMax - 1; i > 0; i--)
i was trying to solve a breadth first search problem on spoj.the problem statement is as follows:
An equidivision of an n × n square array of cells is a partition of the n^2 cells in the array in exactly n sets, each one with n contiguous cells. Two cells are contiguous when they have a common side.
the problem link is:http://www.spoj.com/problems/EQDIV/
my code:http://ideone.com/OjluJG
#include<cstdio>
#include<cstring>
#include<iostream>
#include<sstream>
#include<queue>
using namespace std;
#define pii pair< int, int>
int n, m, grid[105][105];
char inp[101 * 101];
bool inRange(int i, int j)
{
m = n;
return (i >= 0 && i < n && j >= 0 && j < m);
}
int main()
{
int i, j, comp;
scanf("%d", &n);
while (n != 0)
{
if (n == 1)
{
printf("good\n");
scanf("%d", &n);
continue;
}
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
grid[i][j] = 0;
}
}
int a, b, start1[n], start2[n], print = 0, c, d;
queue< pii > Q;
pii p;
getchar();
for (i = 1; i <= n - 1; i++)
{
gets(inp);
stringstream ss(inp);
for (j = 1; j <= n; j++)
{
ss >> a >> b;
if (j == 1)
{
start1[i - 1] = a;
start2[i - 1] = b;
//printf("%d %d\n",start1[i-1],start2[i-1]);
}
grid[a - 1][b - 1] = i;
}
}
for (int x = 0; x < n; x++)
{
int count = 1;
if (x == n - 1)
{
comp = 0;
p.first = c;
p.second = d;
Q.push(p);
}
else
{
comp = x + 1;
p.first = start1[x] - 1;
p.second = start2[x] - 1;
Q.push(p);
}
while (!Q.empty())
{
p = Q.front();
i = p.first;
j = p.second;
Q.pop();
grid[i][j] = -1;
if (x != n - 1)
{
if (inRange(i + 1, j) && grid[i + 1][j] == 0)
{
c = i + 1;
d = j;
}
if (inRange(i - 1, j) && grid[i - 1][j] == 0)
{
c = i - 1;
d = j;
}
if (inRange(i, j + 1) && grid[i][j + 1] == 0)
{
c = i;
d = j + 1;
}
if (inRange(i, j - 1) && grid[i][j - 1] == x + 1)
{
c = i;
d = j - 1;
}
}
if (inRange(i + 1, j) && grid[i + 1][j] == comp)
{
p.first = i + 1;
p.second = j;
Q.push(p);
count += 1;
}
if (inRange(i - 1, j) && grid[i - 1][j] == comp)
{
p.first = i - 1;
p.second = j;
Q.push(p);
count += 1;
}
if (inRange(i, j + 1) && grid[i][j + 1] == comp)
{
p.first = i;
p.second = j + 1;
Q.push(p);
count += 1;
}
if (inRange(i, j - 1) && grid[i][j - 1] == comp)
{
p.first = i;
p.second = j - 1;
Q.push(p);
count += 1;
}
}
if (count != n)
{
print = 1;
printf("wrong\n");
break;
}
}
if (print == 0)
printf("good\n");
//printf("%d %d\n",c,d);
scanf("%d", &n);
}
}
i am getting wrong answer ,don't know why?
can someone provide the testcase for which it is wrong?