I have this integer:
4732891432890432432094732089174839207894362154
It's big so I want to delete all digits in it except the digit 4 and I don't know how. This is my code:
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
unsigned ll n, lastDigit, count = 0;
ll t;
cin >> t;
while(t--)
{
cin >> n;
while (n !=0)
{
lastDigit = n % 10;
if(lastDigit == 4)
count++;
n /= 10;
}
cout << count << "\n";
}
return 0;
}
I used the while loop because I have multiple test case not only that number.
Just to show you current C++ (C++20) works a bit different then wat most (older) C++ material teaches you.
#include <algorithm>
#include <iostream>
#include <string>
#include <ranges>
bool is_not_four(const char digit)
{
return digit != '4';
}
int main()
{
// such a big number iwll not fit in any of the integer types
// needs to be stored in memory
std::string big_number{ "4732891432890432432094732089174839207894362154" };
// or input big_number from std::cin
// std::cout >> "input number : "
// std::cin >> big_number;
// NEVER trust user input
if (!std::any_of(big_number.begin(), big_number.end(), std::isdigit))
{
std::cout << "input should only contain digits";
}
else
{
// only loop over characters not equal to 4
for (const char digit : big_number | std::views::filter(is_not_four))
{
std::cout << digit;
}
// you can also remove characters with std::remove_if
}
return 0;
}
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.
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.
Is there any way to get the length of int variable e.g In string we get the length by simply writing int size = string.length();
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int i = 0;
cout<<"Please Enter the value of i"<<endl;
cin>>i;
//if user enter 123
//then size be 3 .
// Is it possible to find that size
}
#include <cassert>
#include <cmath>
#include <iostream>
using namespace std;
int main () {
assert(int(log10(9)) + 1 == 1);
assert(int(log10(99)) + 1 == 2);
assert(int(log10(123)) + 1 == 3);
assert(int(log10(999)) + 1 == 3);
return 0;}
You have a few options here:
(This answer assumes you mean number of printable characters in the integer input)
Read the input as a string and get its length before converting to an int. Note that this code avoids error handling for brevity.
#include <iostream>
#include <sstream>
using namespace std;
int main(int argc, char** argv) {
cout << "Please enter the value of i" << endl;
string stringIn = "";
cin >> stringIn;
cout << "stringIn = " << stringIn << endl;
size_t length = stringIn.length();
cout << "input length = " << length << endl;
int intIn;
istringstream(stringIn) >> intIn;
cout << "integer = " << intIn << endl;
}
Read in an integer and count the digits directly:
Many other answer do this using log. I'll give one that will properly count the minus sign as a character.
int length_of_int(int number) {
int length = 0;
if (number < 0) {
number = (-1) * number;
++length;
}
while (number) {
number /= 10;
length++;
}
return length;
}
Derived from granmirupa's answer.
Not sure whether it fits your requirement but you could use std::to_string to convert your numeric data to string and then return its length.
For length i assume you mean the number of digits in a number:
#include <math.h>
.....
int num_of_digits(int number)
{
int digits;
if(number < 0)
number = (-1)*number;
digits = ((int)log10 (number)) + 1;
return digits;
}
Or:
int num_of_digits(int number)
{
int digits = 0;
if (number < 0) number = (-1) * number;
while (number) {
number /= 10;
digits++;
}
return digits;
}
Onother option could be this (can works with float too, but the result is not guaranteed):
#include <iostream>
#include <sstream>
#include <iomanip>
...........
int num_of_digits3(float number){
stringstream ss;
ss << setprecision (20) << number;
return ss.str().length();
}
I designed this program that can print the Fibonacci Series (series[i] = series[i-1] + series[i-2]) but i can't get more than 47 numbers because the 48th they become negative and strange numbers (i think this happens when the list is out of range or the item is null):
#include <iostream>
#include <vector>
using namespace std;
int main ()
{
int length;
string again = "";
do {
cout << "Enter the length you want in your sequence: ";
cin >> length;
vector<int> series(length);
for (int n=0; n<=1; n++) series[n] = n;
for (int number=2; number<=length; number++) {
series[number] = series[number-1] + series[number-2];
}
for (int i=0; i<length; i++) cout << series[i] << " ";
cout << endl << "Do it again ? <y/n> ";
cin >> again;
cout << endl;
} while (again == "y");
}
EDIT:
"Improved" code:
#include <iostream>
#include <vector>
#include <string>
std::vector<int> fibonacci (int length)
{
std::vector<int> series(length);
series[0] = 0;
series[1] = 1;
for (int num=2; num<length; num++) {
series[num] = series[num-1] + series[num-2];
}
return series;
}
int main ()
{
std::string again;
do {
std::cout << "Enter how many numbers you want in your series: ";
int length;
std::cin >> length;
std::vector<int> series(length);
series = fibonacci(length);
for (int n=0; n<length; n++) std::cout << series[n] << " ";
std::cout << "\nDo it again <y/n> ? ";
std::cin >> again;
std::cout << std::endl;
} while (again == "y");
}
When you get to the 47th value, the numbers go out of int range. The maximum int value is 2,147,483,647 and the 46th number is just below at 1,836,311,903. The 47th number exceeds the maximum with 2,971,215,073.
Also, as LeonardBlunderbuss mentioned, you are exceeding the range of the vector with the for loop that you have. Vectors start with 0, and so by having number<=length; the range+1 element will be called. The range only goes up to length-1.
You are encountering integer overflow, meaning that you are trying to calculate a number that is outsize of the bounds of INT_MAX and INT_MIN. In the case of an unsigned number, it just overflows to zero and starts over, while in the case of a signed integer, it rolls over to INT_MIN. In both cases this is referred to as integer overflow or integer wraparound.
You could put a band-aid on the solution by using long long int (likely 64-bits on most modern systems) instead of int for your primitive data type, or you could use a better approach like a library that supports (almost) arbitrarily long data types, like libBigInteger.
References
Integer Overflow, Accessed 2014-03-04, <http://en.wikipedia.org/wiki/Integer_overflow>
C++ Big Integer Library, Accessed 2014-03-04, <https://mattmccutchen.net/bigint/>
The limits.h Header File, Accessed 2014-03-04, <http://tigcc.ticalc.org/doc/limits.html>
This is my solution to calculating BIG fibonacci numbers
// Study for algorithm that counts n:th fibonacci number
#include <iostream>
#include <cstdlib>
#include "boost/multiprecision/cpp_int.hpp"
#define get_buffer(a) buffer[(a)%2]
#define BIG boost::multiprecision::cpp_int
int main(int argc, const char* argv[])
{
// atoi returns 0 if not integer
if(argc != 2 || atoi(argv[1]) < 1){
std::cout << "You must provide one argument. Integer > 0" << std::endl;
return EXIT_SUCCESS;
}
// ring buffer to store previous two fibonacci number, index it with [i%2]
// use defined function get_buffer(i), it will do the magic for you
BIG buffer[2]={ 1, 1 };
// n:th Fibonacci
unsigned int fn = atoi(argv[1]);
// count loop is used if seeked fibonacci number is gt 2
if(fn > 2){
for(unsigned int i = 2; i < fn; ++i){
get_buffer(i) = get_buffer(i-1) + get_buffer(i-2);
// get_buffer(i-1) + get_buffer(i-2) == buffer[0] + buffer[1]
// if you want to print out every result, do it here
}
}
// Result will be send to cout
std::cout << "Fibonacci[" << fn << "] is " << get_buffer(fn-1) << std::endl;
return EXIT_SUCCESS;
}
I've written a small program in C++ that prompts the user for input, the user gives a number, then the computer displays the number reversed.
For example: 17 becomes 71. 123 becomes 321.
This is the program:
#include <iostream>
#include <string> //for later use.
using namespace std;
int rev(int x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
return r;
}
int main()
{
int nr;
cout << "Give a number: ";
cin >> nr;
rev(nr);
cout << nr;
return 0;
}
The final result of the program: prints the same number, function has no effect. What am I doing wrong? I tried several solutions but to no avail.
You need to change rev(nr); to nr = rev(nr);
or alternately change your function to:
void rev(int& x)
{
int r = 0;
while(x)
{
r = (r*10) + (x%10);
x = x/10;
}
x = r;
}
You're doing it right, but you're not grabbing your return value (the reversed value).
To solve this, just assign or print the return value:
cout << rev(nr);
or
nr = rev(nr);
cout << nr;
While probably not in the intended spirit, the simple answer is that if you're only going to display it in reverse, you can cheat and just work with a string:
std::string input;
std::cin >> input;
std::cout << std::string(input.rbegin(), input.rend());
You're not actually using the value that rev returns. You're just using the value nr which you pass to rev, and since you don't pass by reference, rev isn't being affected locally.
What you want to say is:
int nr;
cout << "Give a number: ";
cin >> nr;
int result = rev(nr);
cout << result;
return 0;
There is a std::reverse function in the STL, which works with collections.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
long int i = 0;
do {
std::cout << "Gimme a number: " << std::endl;
} while (not (std::cin >> i)); // make sure it *is* a number
std::string display = std::to_string(i); // C++11
std::reverse(display.begin(), display.end());
std::cout << display << "\n";
}