I wanted to solve a problem, yet my code passes only 8 out of 10 tests. The problem is to determine whether a number 1<=N<=10^9 can be a numeric polyndrome. The thing is, you may add as many leading zeros as it requires to make a non-polyndrome into a polyndrome. If it is possible, or a number is polyndrome, the result must be yes, otehrwise no. For example, 2020 is not a polyndrome, but If I add a leading zero, it becomes 02020, which is a polyndrome. One main problem of my code is that i don't know the number of leading zeros needed to make a number a polyndrome. Here's my code:
#include <cstdio>
#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
string N, N2;
cin >> N;
N2 = N;
reverse(N.begin(), N.end());
if (N2 == N) {
cout << "Yes" << "\n";
return 0;
}
else {
N2 = "0" + N2;
N = N + "0";
if (N != N2) {
cout << "No" << "\n";
return 0;
}
else {
cout << "Yes";
return 0;
}
}
}
I would be grateful for any help to enhance my code!
edit: I have to add leading zeros if it can turn a number into a polyndrome, that's the main thing
I would do something like:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
string n;
cin>>n;
string m =n;
reverse(n.begin(),n.end());
if(n==m){
cout<<"Yes"<<endl;
return 0;
}
int count=0;
int k=m.length();
for(int i=1; i<=k;i++){
if(m[i]=='0'){
count+=1;
}
}
for(int i=1;i<=count;i++){
m='0'+m;
}
string m2=m;
reverse(m.begin(), m.end());
if (m2 == m)
{
cout << "Yes" << endl;
return 0;
}
else{
cout << "No" << endl;
return 0;
}
}
Just to be complete, I will show you the answer based on the comments.
It is the same, if you add 0es to the beginning or remove them from the end.
If you have 2020, you can either add one leading 0 --> 02020 or remove a trailing 0 -> 202. Result is the same.
So, the algorithm will be.
Search from the right end for the first character that is not '0'
Build a pair forward and a pair reverse iterators, based on the iterator, found by `std::find
Compare temporary created strings, build from forward and reverse iterators
Output comparison result
Very simple example code:
#include <iostream>
#include <string>
#include <iterator>
#include <algorithm>
int main() {
if (std::string numberAsString{}; std::cin >> numberAsString) {
std::string::reverse_iterator newEnd = std::find_if(numberAsString.rbegin(), numberAsString.rend(), [](const char c) {return c != '0'; });
std::cout << (std::string(numberAsString.begin(), newEnd.base()) == std::string(newEnd, numberAsString.rend()) ? "Yes\n" : "No\n");
}
}
I only changed in main else part of your code.
1. Now understand if some numerical string is not palindrome and you are going to make it palindrome by adding leading 0's then it must end with 0's.
For Ex. 100 is not palindrome but you can make it by 00100 it possible because two 0's present at end.
same with 10 -> 010
2. some numbers which are ends with 0's and not palindromes but we can make them by adding leading 0's
10, 20, 30.....90 -> (respective palindrome) 010,020,.....090
100, 110, 200, 220,.....900, 990 -> (respective palindrome) 00100, 0110, 00200, 0220.....00900, 0990
3. some numbers which are ends with 0's and not palindromes and we can't make them by adding leading 0's
120, 130...190
210, 230, 240,....290
.
.
.
11010
4.
Now if you see carefully the numbers which we can make palindrome you get that to be able to do so we have to add exact number of 0's at starting as present at the end. if you pause for minute and think then you get logical sense too.
5.
Now I am creating condition to right code on above analysis. I will talk about just else part
i> So I will check first that how many 0's present at end of number(while loop). at least one 0's must be present.
ii> Then I am adding as many leading 0's present at end.( for loop).
iii> Then storing N2 in N3 so I can reverse and check palindrome become or not because all numbers end with 0's do not become palindromes.
Code
#include <iostream>
#include <algorithm>
#include<string>
using namespace std;
int main()
{
string N, N2;
cin >> N;
N2 = N;
reverse(N.begin(), N.end());
cout<<N<<" "<<N2<<"\n";
if (N2 == N)
{
cout << "Yes" << "\n";
return 0;
}
else
{
int k=N2.length(), count=0, i=1;
while(N2[k-i]=='0')
{
count++;
i++;
}
if(count==0)
{
cout<<"No";
return 0;
}
for(int i=1; i<=count; i++)
{
N2="0" + N2;
}
string N3=N2;
reverse(N2.begin(), N2.end());
cout<<N3<<" "<<N2<<"\n";
if (N3 != N2)
{
cout << "No" << "\n";
return 0;
}
else
{
cout << "Yes";
return 0;
}
}
}
Also just note that you added <cstdio> two times even it didn't required one time also. Sometime if you include same header file twice it might cause error. Also there is no requirement of <cmath> library file. By the way you didn't include <string> library file might be in some cases your program run quite well without including it but it is not standard practise.
Related
Needle in the haystack. I'm a beginner in programming and we only learned a thing or two so far, barely reached arrays yet.
Input: 1 4325121
Output: 2
Input two values in one line. The first one shall accept any integer from 0-9 and the other one shall take a random positive integer.
Using a while loop, count how many of the first integer (0-9) is present in the digits of the second inputted integer and print the result.
No arrays to be used here, only while loops and else-if conditions with basic coding knowledge and without the use of advanced coding.
As you said, you need to keep it as simple as possible. Then this can be a solution:
#include <iostream>
int main()
{
int first { };
int second { };
std::cin >> first >> second;
int quo { second };
int rem { };
int count { };
while ( quo > 0 )
{
rem = quo % 10;
quo /= 10;
if ( first == rem )
{
++count;
}
}
std::cout << "Result: " << count << '\n';
}
Using while loop
#include <iostream>
using namespace std;
int main()
{
int a = 1;
int b = 4325121;
int count = 0;
while(b > 0)
{
int m = b % 10;
if(m == a)
{
count++;
}
b /= 10;
}
cout << count;
return 0;
}
Nice little problem. But actually, to keep it as simple as possible no calculations are needed at all. I simplified my example, and it just keeps working on the input text, which is 100% sufficient to solve the problem:
#include <iostream>
#include <string>
using namespace std;
int main() {
char digit;
std::string number;
cout << "Input: ";
cin >> digit >> number;
int count = 0;
for (char const character : number)
if (character == digit)
count++;
cout << "Result: " << count << endl;
return 0;
}
Given the question, this code solves the problem.
This question already has answers here:
Counting the number of occurrences of a string within a string
(5 answers)
Closed 2 years ago.
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int count = 0;
vector<string> v;
string resp;
cin >> resp;
v.push_back(resp);
for(int i = 0; i < v.size(); i++){
if(find(v.begin(), v.end(), "xy") != v.end()){
count++;
}
cout << count << endl;
}
return 0;
}
I want to find the character "xy" in the string for multiple test cases.
For input xy, my count value outputs correctly as 1.
But for the input xyxxy instead of 2 it gives the value as 0
It is only finding the value once but i want to check the count of xy in whole string
I tried to use the substring function as well but it failed to work
I don't get the idea of while loop but that worked for me.
#include <iostream>
#include <vector>
int main()
{
std::string str;
std::cin >> str;
int count = 0;
for (int i(0); i < str.size()-1; ++i)
{
if ((str[i] == 'x') && (str[i + 1] == 'y'))
{
++count;
}
}
std::cout << count;
}
You're looking for "xy" within a vector of strings, which in your example, has a single element, "xyxxy". Since "xy" is not equal to "xyxxy", you're not finding any matches.
But even if you tried to std::find "xy" within "xyxxy" itself - that would fail too, since std::find looks for a single element within a range (or rather, iterator pair).
Instead, you can use the string::find() method, as described here; or, as the case may be, std::string_view::find():
#include <string>
#include <vector>
#include <iostream>
#include <string_view>
int main() {
const std::string needle{"xy"};
std::string haystack;
std::cin >> haystack;
std::size_t count{0};
std::string_view remainder{haystack};
while(true) {
auto first_pos = remainder.find(needle);
if (first_pos == std::string_view::npos) { break; }
count++;
remainder = remainder.substr(first_pos+needle.length());
}
std::cout << "Found " << count << " occurrences of \"" << needle << "\"\n";
}
Note: This does not account for overlapping occurrences. If you want those, you could either always increase the starting position by just 1; or make your solution more complex by employing something Boyer-Moore or Knuth-Morris-Pratt search (see String search algorithms), and resuming it at the correct state after each occurrence found.
The following code is for a homework assignment due on 17 October. The problem states to "write a program with a loop that lets the user enter a series of numbers. After all the numbers have been entered, the program should display the largest and smallest numbers entered."
#include "stdafx.h"
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;
bool isNumeric(string aString)
{
double n;
istringstream is;
cin >> aString;
is.str(aString);
is >> n;
if (is.fail())
{
return false;
}
return true;
}
vector<double> limits(vector<double> a)
{
// Returns [min, max] of an array of numbers; has
// to be done using std::vectors since functions
// cannot return arrays.
vector<double> res;
double mn = a[0];
double mx = a[0];
for (unsigned int i = 0; i < a.size(); ++i)
{
if (mn > a[i])
{
mn = a[i];
}
if (mx < a[i])
{
mx = a[i];
}
}
res.push_back(mn);
res.push_back(mx);
return res;
}
int main()
{
string line = " ";
vector<string> lines;
vector<double> arr;
cout << "Enter your numbers: " << endl;
while (!line.empty() && isNumeric(line))
{
getline(cin >> ws, line);
if (line.empty() || !isNumeric(line))
{
break;
}
lines.push_back(line);
transform(line.begin(), line.end(), line.begin(), [](char32_t ch) {
return (ch == ' ' ? '\000' : ch);
}); // Remove all spaces
arr.push_back(atof(line.c_str()));
}
vector<double> l = limits(arr);
cout << "\nMinimum: " << l[0] << "\nMaximum: " << l[1] << endl;
return 0;
}
The above code is what I have. However, it's not always outputting the correct maximum value and only outputs "0" for the minimum value. I can't seem to find what's wrong with this so if anyone could help that would be great.
For the minimum, your problem appears to be with the fact that in your limits() function, you initialize the value of min to 0. So if you have an array of [1, 2, 3, 4], it will check each element and, seeing that none of them is less than 0, leave 0 as the minimum. To fix this, you can set the initial value of mn to the first element of the array. Note that you will have to check to make sure the array has at least one element to avoid a possible overflow error.
For the maximum, I'm not sure what kind of inconsistencies you're having, but if your array only contained negative values, you would have the same problem as with minimum, where the initial value is higher than any of the actual values.
So I'm studying c++ from the book ((C++ without fear)). and there's a code I didn't understand. I need to know how the code works. my problem is in the loop, I understand how it works, but I didn't understand how would it work with adding 1 to i. (EVEN WITH COMMENTS).
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n = 0; // Number to test for prime-ness
int i = 2; // Loop counter
bool is_prime = true; // Boolean flag...
// Assume true for now.
// Get a number from the keyboard.
cout << "Enter a number and press ENTER: ";
cin >> n;
// Test for prime by checking for divisibility
// by all whole numbers from 2 to sqrt(n).
while (i <= sqrt(n)) {
if (n % i == 0) { // If i divides n,
is_prime = false; // n is not prime.
}
++i; // Add 1 to i.
}
// Print results
if (is_prime) {
cout << "Number is prime." << endl;
}
else
{
cout << "Number is not prime." << endl;
}
return 0;
}
Adding 1 to i is simply to move on to test the next number the next time round the loop to test if it divides n. ++i is simply the prefix increment operator being invoked. Postfix i++; could be used here for the same effect, as could i = i + 1;, but since there exist some cases where prefix increment is faster than the alternatives (not the case here) it's usually a good habit to use prefix increment always unless you have a specific reason not to do so.
I'm struggling to apply a "While" loop to the following problem: Design the logic for a program that allows a user to enter a number. Display the sum of every number from one through the entered number.
Start
int userNumber;
Declarations
int number = 1
while number <= userNumber
++number
endwhile
output number
Stop
I know my code isn't correct as it is just adding one to the initial value until the user's number is reached, thus making the output the user's number. How would I go about adding each subsequent value without writing them out e.g. user's number is 10, so the program would add 1+2+3+4+5+6+7+8+9+10 and output the total of 55?
Thank you!
Here's a tip. You'll want to start at the users number and count down to 0. Like this:
int finalNum = 0;
int userNum;
//This is where you need to get the user's number....
while(userNum > 0)
{
finalNum += userNum;
userNum--;
}
//Do whatever you need to finalNum....
EDIT: It appears you've posted pseudocode; usually a big no-no here unless stated otherwise. It's better to post the actual code as it's easier to tell what exactly is going on.
The function you need could look like this for c++:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
unsigned t = 0; // Assume the result to be 0 (zero)
for (i = 1; i <= x; i++) // Continue until i is greater than x
{
t += i; // Accumulate, i.e. t = t +i
}
cout << "sum=" << t << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
An alternative is:
#include <iostream>
using namespace std;
void calc(unsigned x)
{
cout << "sum=" << (x*(x+1)/2) << endl; // Print the result
}
int main()
{
calc(10);
return 0;
}
This works because the sum of all integers from 1 to n is n*(n+1)/2