im simple asking if this is ok. i was asked to do the following. Write a program that will continuously ask the user for positive integers (until the
user enters a negative integer at which the program will be terminated). Every
time the user inputs a positive integer the program will print out this integer in
reverse. Your program should have a function that accepts and integer and returns
an integer in reverse. To convert the integer to its reverse, your program will call
this function. at the end of each output i keep getting 0. please explain why. also if i use void main with the function i get garbage. please explain why. thanks in advance
this is my code....
#include<iostream>
#include<cstdlib>
using namespace std;
int reverseNum(int num){
for(int j=num; j>0; j--)
cout<<j<<" ";
cout<<endl;
return false;
}
int main(){
double enternum = 0;
do{
cout<<"Enter a positive number > 0, to begin countdown ";
cin >>enternum;
cout<<reverseNum(enternum);
cout<<endl;
}
while(enternum>0);
if(enternum<=0)
cout<<"Invalid entry, good bye.";
cout<<endl;
return 0;
}
because of this: return false; - I'll leave it to you to figure out the rest..
The function is supposed to reverse the integer and then return the result. For example, if the input is 123, then the function returns 321.
Your function outputs a count-down and returns 0 (=false).
To reverse a number, you can a) convert it to string, reverse the string, convert it back to integer; b) do it on integers directly with mathematical division / multiplication / addition / modulo operations.
In C++, you don't use void main().
A 0 because when you return false, the result of type bool is implicitly converted to an int and gets printed at the line cout<<reverseNum(enternum);
Also, In this line, double enternum = 0; you want an integer int.
From your text I thought the program was working as intended, but from reading the code I suppose it just counts down from the number. Was this what you wanted?
I'd have implemented it like this (and here the function returning an integer makes sense too):
int reverseNum(int num)
{
int reverse = 0;
[...] // Do the actual reversing
return reverse;
}
Your program should have a function that accepts and integer and returns an integer in reverse
your reverseNum function should return the reversed integer, not false. and it shouldn't print the number as well, it's the caller which supposed to print it.
if one does:
i = reverseNum(1234);
then i should contain 4321 as an integer (NOT string).
the reason you keep getting 0 is because false is equivalent to 0 as an integer.
You should read the C++ FAQ in its entirety. You should especially read this. You should also learn how to debug your code. If you stepped through your code in a debugger then all the answers that you have been given here will be obvious.
For good fun, I attempted a generic implementation that supports any integral or floating point type supported by your compiler.
Be warned, there are a number of issues:
reversing a floating point number is not well defined semantically (how to position the decimal separator? How do we handle exponential notation?)
floating point types are frequently inexact (at least common IEEE formats are) and hence scaling the input will introduce artificial fractional digits. I have not taken much effort to do proper rounding, so some numbers will reverse into strange things (e.g. 123.0 could reverse into 992.1 instead of 321.0 (untested for this input, try some yourself))
the implementation is laughably template-happy. Think of it as the instructional part of this playful answer.
Oh, uncomment the DEBUGTRACE definition to ... get debug tracing :)
See it live here [click]TM
#include <cmath>
#include <limits>
#include <iostream>
#define MAX_DECIMAL_FRACTION 5
#define DEBUGTRACE(x) // do { std::cerr << x; } while (false)
template <typename T, bool is_integer> struct reverse_impl;
template <typename T>
struct reverse_impl<T, true>
{
static T reverse(T input)
{
T output;
for (output = 0; input; input/=10)
output = (output * 10) + input % 10;
return output;
}
};
template <typename T>
struct reverse_impl<T, false>
{
static T reverse(T input)
{
if (std::abs(input) <= std::numeric_limits<T>::epsilon())
return T(0);
// scale input
int log10 = (int) (std::log(input)/std::log(T(10)));
input *= std::pow(10, MAX_DECIMAL_FRACTION);
input = std::floor(input);
input /= std::pow(10, log10+MAX_DECIMAL_FRACTION);
DEBUGTRACE("debug: scaled " << input << " digits: ");
int iteration = std::max(log10+MAX_DECIMAL_FRACTION, MAX_DECIMAL_FRACTION);
if (std::floor(input) < 1)
{
input *= 10;
iteration--;
}
T output;
for (output = T(0);
iteration-- && std::floor(input) >= 1;
input-=std::floor(input), input*=T(10))
{
output = (output / T(10)) + std::floor(input);
DEBUGTRACE(std::floor(input));
}
DEBUGTRACE(std::endl);
return output * std::pow(10, log10);
}
};
template <typename T>
T reverse(T input)
{
return reverse_impl<T, std::numeric_limits<T>::is_integer>::reverse(input);
}
int main()
{
std::cout << reverse(-123l) << std::endl;
std::cout << reverse(123ul) << std::endl;
std::cout << reverse(123456.0) << std::endl;
std::cout << reverse(0.027f) << std::endl;
return 0;
}
***//here is the simple solution to find reverse of a function***
#include<iostream.h>
#include<conio.h>
void main()
{
int n,a,c,d,b;
clrscr();
cout<<"enter five integers";
cin>>n;
a=n/10000;
n=n%10000;
b=n/1000;
n=n%1000;
c=n/100;
n=n%100;
d=n/10;
n=n%10;
cout<<"number in reverse order is"<<n<<d<<c<<b<<a;
getch();
}
Related
I am working on this LeetCode problem to take an integer and reverse it, given that the reversed in is within the signed 32-bit range, in which case we should return 0.
and this code is doing just that, even with numbers like 1534236469/-1534236469. Except when it comes to tricky numbers like -2147483648 where its not recognising it as out of range and instead returning 8 and not 0.
I know this is not the cleanest code, but can you help me recognise what I'm missing?
#include<iostream>
#include<limits>
using namespace std;
class Solution {
public:
int reverse(int x) {
int a, r, y;
string num, fnum;
a = abs(x);
try{
while(a != 0){
r = a % 10;
a = a / 10;
num = to_string(r);
fnum = fnum + num;
y = stoi(fnum);
}
} catch(out_of_range& oor){
return 0;
}
if(x==0){
return 0;
} else if (x<0){
return -y;
} else {
return y;
}
}
};
int main(){
Solution mine;
cout << mine.reverse(-2147483648);
}
[...] when it comes to tricky numbers like -2147483648 where its not recognising it as out of range and instead returning 8 and not 0.
That number is "tricky" because it's equal to std::numeric_limits<int>::min() in your environment and given a two's complement representation of type int, it happens that std::abs(-2147483648) == -2147483648.
Next in your (contrived, I must say, there's no need to use a string here) code, the line num = to_string(r); would result in num = "-8", so that the loop would compose a string like "-8-4-6-3-8-4-7-4-1-2".
When applyed to strings like that, stoi doesn't throw an exception, it just stops parsing (you would have noticed it by passing and inspecting its other parameters).
If you want to check if the result is outside the range of an int, you could use locally a wider type (e.g. long long) and check the boundaries after the calculations or keep using int, but compare all the intermediate values with the limits before any calculation.
I have to code a program in which a user input some number and the program have to swap the first digit form last number.
For Example user inputs: 12345
The expected output would then be: 52341
But I am getting an error and getting output like: 4465
This is my Code:
#include <iostream>
#include <cmath>
using namespace std;
void main()
{ int num,ln,fn,pw,dg,swap;
cin >> num;
ln = num%10 ;
dg = log10(num);
pw = pow(10,dg);
fn = num%pw;
swap = ln*pw;
swap = swap+num/pw;
swap = swap-ln;
swap = swap+fn;
cout << swap << endl;
system ("pause");
}
Help me to solve this.
Ok I'll do it.
0. Design choice(s)
The operation you want to do is not on the value of the input number but rather on its representation, specifically in base 10. We'd better go for a string manipulation then.
1. Integer to string
With C++11 and following, we do have std::to_string: takes an integer, returns a string, done.
2. Accessing characters from a string
If the string is not empty, std::string::front() and std::string::back() return a reference to the first and last characters of that string, easy.
3. Swapping characters
We have the utility std::swap and the swap idiom
using std::swap;
swap(lhs, rhs);
lhs and rhs being what needs to be swapped (see step 2.).
4. Back to integer
We have std::stoi doing what std::to_string does but in reverse, done. But what if the new integer has become too big to be held by an integer type?
5. Putting all together
Let's define a (free) function!
int reverse_border_digits(int value)
{
// steps 1 through 4
return result;
}
Here's an answer fulfilling the OP requirements
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int num;
cin >> num;
int dg = (int)(log10(num + 0.000001)); // add small delta to avoid any possible rounding error on an exact power of ten
int pw = (int)round(pow(10.0, dg));
int swap = (num % 10) * pw + (num - num % 10 - (num / pw) * pw) + num / pw;
cout << swap << '\n';
}
I compiled and run in my computer, and it executes correctly. I tried IDEONE, and I got a successful answer.
But when I submit it in SPOJ, I'm getting a wrong answer. Is something wrong in this implementation?
#include <iostream>
#include <cstdio>
using namespace std;
int factorial(int n) {
if (n <= 1)
return 1;
return n * factorial(n - 1);
}
int main() {
int t;
int n;
cout << "";
cin >> t;
for (int i = 0; i < t; i++) {
cout << "";
cin >> n;
printf("%d\n", factorial(n));
}
return 0;
}
The problem with the above code is due to the finite space we can use to store the value of an int. On a 32-bit machine, int's have 32 bits (value 0 or 1), which means that the maximum value an unsigned int can have is (2^31 - 1) and the maximum value an int can have is (2^30 - 1) (since it needs one bit to denote whether it is positive or negative, while the unsigned int is always positive and can devote that bit to just regular value).
Now, that aside, you should look into ways of storing the value of a very large number in a different data structure! Maybe an array would be a good choice...
Just to brainstorm, imagine creating an int bigInteger[100] (that should be large enough to hold 100!). To multiply two of your numbers, you could then implement a bitMultiplication(int bitNum[], int num) function that would take in your array by reference and perform bitwise multiplication (see the following post for details: Multiplying using Bitwise Operators).
Use that bitMulitiplication(int bitNum[], int num) instead of the regular multiplication in your recursive factorial function, and you should have a function that works on large n!
I want to use an if condition that executes a line of code depending on whether or not a certain double has an integer value:
int A;
int B;
int C;
double X;
cout << "Enter three values: " << endl;
cin >> A >> B >> C;
X=A*B*C;
X=sqrt(X);
if (X holds an integer value){
//Do this
}
else if (X does not hold an integer value){
//Do this instead
}
Basically I can't work out how to write the if condition. Is there a simple syntax I can use to do this, or do I need to add some separate code to check the double and then pass a boolean to the if condition?
Many thanks in advance. I have checked elsewhere on here but can only find examples where people wanted to cout the result of the check, rather than use it in a condition. This was generally done by truncating the double in some way or examining it as a string, none of which will work here I believe.
I am working in Visual Studio 2013 and Windows 8.1.
Any help appreciated.
[Edit: I've added the sqrt function alluded to in the comments to the accepted solution]
This is one of the main uses of modf:
bool
isInt( double d )
{
double dummy;
return modf( d, &dummy ) == 0.0;
}
Of course, this solution is exact; in many cases, you'll want to accept some sort of epsilon, since the floating pont arithmetic won't have been exact.
Round the double and compare it to the original double. I.e.,
if(fabs(round(X) - X) < 0.001)
Obviously, you can change the tolerance to whatever you feel is acceptable. Also, as crashmstr pointed out in the comments, there is no way to get a non-integer value if you multiply three integers.
Create a simple function:
bool isInt(double n) {
if (int (n) == n)
return true;
else
return false;
}
Is this what you are looking for ?
string x = "42";
int value;
if(int.TryParse(x, out value))
// Do something
I'm currently working on an algorithm to find all numbers with 9 digits using numbers 1-9 without any repeats. I'm testing a theory I have that filtering numbers as such will make for a more efficient sudoku checker.
The code that I implemented does the following. It uses a for loop for places 1-9 in a number, such that (a)(b)(c)(d)(e)(f)(g)(h)(i) = #########.
My theory is that by checking if the sum of the numbers (a-i) is equal to 45, that the product of a through i is equal to 9! and that the sum of the inverses of a-i is equal to roughly 2.828968 (or 1 + 1/2 + 1/3 ... 1/9)
The issue is that after I filter the 9-digit numbers by the sum of the inverses of a-i, the count of possible 9-digit numbers predicted is less than 9! (the actual amount of possible numbers). I'm not sure why it's filtering so much, but the numbers that it does catch do not have any repeats (which is good).
My thoughts are that the way I am playing with doubles is messing up the algorithm.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int product;
int sum;
int count=0;
double inverseSum;
double correctInverseSum=(1.0/1.0)+(1.0/2.0)+(1.0/3.0)+(1.0/4.0)+(1.0/5.0)+
(1.0/6.0)+(1.0/7.0)+(1.0/8.0)+(1.0/9.0);
for(double a=1.0; a<10.0; a++){
for(double b=1.0; b<10.0; b++){
for(double c=1.0; c<10.0; c++){
for(double d=1.0; d<10.0; d++){
for(double e=1.0; e<10.0; e++){
for(double f=1.0; f<10.0; f++){
for(double g=1.0; g<10.0; g++){
for(double h=1.0; h<10.0; h++){
for(double i=1.0; i<10.0; i++){
product=a*b*c*d*e*f*g*h*i;
sum=a+b+c+d+e+f+g+h+i;
if(product==9*8*7*6*5*4*3*2*1 && sum==45){
inverseSum=(1.0/a)+(1.0/b)+(1.0/c)+(1.0/d)+
(1.0/e)+(1.0/f)+(1.0/g)+(1.0/h)+(1.0/i);
if(inverseSum==correctInverseSum)
{
count++;
}
}
}
}
}
}
}
}
}
}
}
cout<<"This is the count:"<<count<<endl;
return 0;
}
Now that I washed my eyes after seeing so many for loops, I'd say a candidate is:
if(inverseSum==correctInverseSum)
doubles aren't exactly representable, so you'll have to check for equality using a small epsilon. Something like:
if (fabs(inverseSum - correctInverseSum) < std::numeric_limits<double>::epsilon())
You'll need to #include <limits>.
You're going to need some error tolerance in your checking:
if(fabs(inverseSum-correctInverseSum) < 1e-6) count++
Alternatively, multiply through by 9!, you get
b*c*d*e*f*g*h*i + a*c*d*e*f*g*h*i ...
(one missing factor in each term the sum). Then you can use integer arithmetic instead of floats.
Let's run a quick experiment: Let's try to compute the inverse sum from big to small and in reverse order:
#include <algorithm>
#include <numeric>
#include <iostream>
#include <iterator>
#include <vector>
struct generator
{
generator(): d_value() {}
double operator()() { return 1.0 / ++this->d_value; }
double d_value;
};
int main()
{
std::vector<double> values;
std::generate_n(std::back_inserter(values), 9, generator());
double ordered(std::accumulate(values.begin(), values.end(), 0.0));
double reversed(std::accumulate(values.rbegin(), values.rend(), 0.0));
std::cout << "ordered=" << ordered << " "
<< "reversed=" << reversed << " "
<< "difference=" << (reversed - ordered) << " "
<< "\n";
}
If this where exact math, clearly this should yield the same sum. After all, they are the same set of values. Unfortunately, it turns out that the values are not exactly the same. Here is the output it shows for me:
ordered=2.82897 reversed=2.82897 difference=4.44089e-16
The problem is that the values are not exact and adding two of these non-exact values introduces some error. Often the error doesn't matter too much but trying to compare the results for identity won't work: depending on the order of the operations different operands with different rounded results are involved.
An old adage, but please: Don't repeat yourself.
Keep it DRY.
When you find yourself writing this kind of code you should ask yourself why Do I need to repeat myself in this way.
There are plenty of other options.
1 - recursion. get yourself comfortable with the concept.
2 - the mod operator for i = 0 to 100 r = i % 10, c = i / 10
3 - reevaluating the problem. You are trying to solve a problem that is harder than necessary
Haven't you heard about std::bitset? You only need nine bits to verify, which is probably within your budget.
I've been meaning to get some practice with variadic templates, so I wrote this for you: (c++11 experts, feel free to rip it to pieces.)
#include <bitset>
#include <iostream>
template<unsigned long i>
bool test_helper(std::bitset<i> seen) {
return seen.count() == i;
}
template<unsigned long i, typename T, typename... Args>
bool test_helper(std::bitset<i> seen, T arg1, Args... args) {
return test_helper(seen.set(arg1 - 1), args...);
}
template<typename... Args>
bool test(Args... args) {
return test_helper(std::bitset<sizeof... (Args)>(), args...);
}
template<unsigned long size, bool done = false>
struct Counter {
template<typename ... Args>
unsigned long operator()(Args... args) {
unsigned long count = 0;
for (int a = 1; a < 10; ++a)
count += Counter<size, size == sizeof...(Args)+1>()(a, args...);
return count;
}
};
template<unsigned long i>
struct Counter<i, true> {
template<typename ... Args>
unsigned long operator()(Args... args) {
return test(args...);
}
};
int main(int argc, char** argv) {
std::cout << Counter<9>()() << std::endl;
return 0;
}
If you really insist on using complicated and heuristics, you could also get some experience with rational arithmetic to compute your inverse sum. It should be clear sum of 1/ai is Σj (Πi ai)/aj all divided by Πi ai; you're already computing the denominator, so it only is necessary to compute the numerator, whose maximum value is 99. But, still, the bitset solution seems a lot simpler to me.