Swap first with Last - c++

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';
}

Related

Why is my answer off for certain values of binary representation provided?

The question basically asks us to convert the input binary string (only 1 and 0 provided).
Input format is as follows (each separate point is a new line):
Number of test cases
2N lines with: Length of binary string, Binary string on each alternative line
Output is to return the decimal conversion of the string.
My code:
#include <iostream>
#include <cmath>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int len;
cin >> len;
long long num = 0;
while(len--){
char digit;
cin >> digit;
num += (digit-'0')*pow(2,len);
}
cout << num << endl;
}
return 0;
}
Ik there are other methods to go about this problem, but i want to know whats the problem in mine. Inputting certain values like '10001011111110111010111011010011011011110001011000011101' gives an answer '39401750052935200' when the correct value is '39401750052935197'.
Other examples of wrong output:
269908306298371776 (correct = 269908306298371795)
1152921504606846976 (correct = 1152921504606846975)
My code runs correct for all smaller values of binary input (of length maybe less than 50). Why does it fail for such larger values by such a small margin?
runs correct for all smaller values of binary input (of length maybe less than 50).
num += (digit-'0')*pow(2,len); is like
num = num + (digit-'0')*pow(2,len);
and the addition is done using double math with its 53-ish bit precision infected by pow().
Instead only use integer math:
unsigned long long num = 0;
...
num = num*2 + (digit-'0');

Using function decimal to return only decimal of input as double C++

I am on week 3 of C++ & I am so lost. I need to write a program with function decimal - that will return the decimal part of any non negative decimal number sent to it as input. Needs to be clear that it needs to return a double - parameters set at double.
we haven't learned about function decimal yet nor type coercion and trying to teach myself isn't going well.
Check the following example. You can try something like this that is pretty simple.
double num = 23.345;
int intpart = (int)num;
double decpart = num - intpart;
printf("Num = %f, intpart = %d, decpart = %f\n", num, intpart, decpart);
You can use string conversions:
#include <algorithm>
#include <iostream>
#include <string>
int main() {
float input = 12.123456;
std::string ip = std::to_string(input);
ip.erase(ip.begin(), --std::find(ip.begin(), ip.end(), '.'));
ip.front() = '0';
std::cout << ip;
return 0;
}
Another way would be simply substracting the floor of the number from itself...
#include <iostream>
#include <cmath>
int main() {
float input = 12.12;
std::cout << (input - std::floor(input));
return 0;
}
I'm not quit sure that I'm fully understand your question.
Are you having an hard time implementing this function?
If so - think about subtracting the integral part of the number from it, and in that way you will remain with the decimal part only.
Something like: (pseudo code)
double a = 10.85
int b = int(a)
return a - b
Think about the math.
A decimal number is of form a.b where a is the integral part and b the fractional part.
Suppose your input is N (= 1.234) then to extract say frac = .234 you just need to do is
frac = N - floor(N); remember floor(N) is of 1.000.
I think this is of help implement the code.
An example:
#include <iostream>
#include <cmath>
int main() {
float input;
std::cin >> input;
std::cout << (input - std::floor(input));
return 0;
}
or
as a function
#include <cmath>
double decimal(const double &N){
return (N - std::floor(N));
}

How to swap first and last digit in number in c++

I don't understand why the following code always answers with 0.
#include <iostream>
using namespace std;
int main() {
int n,a,b;
cin>>n;
b=n%10;
while(n!=0) {
a=n%10;
n=n/10;
}
a=b;
b=a;
cout<<n<<endl;
return 0;
}
To swap two numbers, you need a temporary register
tmp=a;
a=b;
b=tmp;
However, if you are trying to swap digits in n, you need to change n. Which you have destroyed in your loop. Keep a copy of it beforehand?
Or simply note that floor(log(n)/log(10)) gives you the power of 10 for the first digit.
n=23456;
int firstdec = pow(10,floor(log(n)/log(10))); // eg 10000
int firstdig = n/firstdec; // eg 2
int lastdig = n%10; // eg 6
int removed = ((n-firstdig*firstdec)/10)*10 ; // eg 3450
int final = removed + lastdig*firstdec + firstdig; // eg 63452
This
a=b;
b=a;
looks nice.
Do you mean swap(a, b) or
int t = a;
a = b;
b = t;
?
And you're not actually changing n.
#include <iostream>
#include<math.h>
using namespace std;
int main()
{
int num, swno;
int fd, ld, digits;
// Reads a number from user
cout<<"Enter any number:";
cin>>num;
ld = num % 10; //Gets last digit
digits = (int)log10(num); //Total number of digits - 1
fd = (int)(num / pow(10, digits)); //Gets the first digit
swno = ld;
swno *= (int)pow(10, digits);
swno += num % ((int)pow(10, digits));
swno -= ld;
swno += fd;
cout<<"\nOriginal number = "<<num;
cout<<"\nNumber after swapping first and last digit: "<<swno;
return 0;
}
You code has some problems, like the variable swap. But also, you seem to expect that by changing a and b, n is changed accordingly, which is not going to happen.
First, because a and b are not references to the digits, they are mere copies. Second, you destroyed you n in the loop finding a, so even when you fix you swap the code will still print 0.
My recommendation is to convert the integer to a string, change the first and last, and then convert it back. It will be much simpler and more readable.
In order to do that you should take a look at stringstreams.
#include <iostream>
#include<string.h>
using namespace std;
int main(void){
int a;
char k,l;
cin>>a;
string s=to_string(a);
k=s[0];
l=s[s.length()-1];
s[0]=l;
s[s.length()-1]=k;
cout<<s;
return 0;
}
Here is what is missing in your code. real= entered value, first and last digits = firstd and lastd and i = number of digits of the entered number.
real -= lastd;
real += firstd;
real -= (firstd*i);
real += (lastd*i);

print number in reverse

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();
}

How to convert an int to a binary string representation in C++

I have an int that I want to store as a binary string representation. How can this be done?
Try this:
#include <bitset>
#include <iostream>
int main()
{
std::bitset<32> x(23456);
std::cout << x << "\n";
// If you don't want a variable just create a temporary.
std::cout << std::bitset<32>(23456) << "\n";
}
I have an int that I want to first convert to a binary number.
What exactly does that mean? There is no type "binary number". Well, an int is already represented in binary form internally unless you're using a very strange computer, but that's an implementation detail -- conceptually, it is just an integral number.
Each time you print a number to the screen, it must be converted to a string of characters. It just so happens that most I/O systems chose a decimal representation for this process so that humans have an easier time. But there is nothing inherently decimal about int.
Anyway, to generate a base b representation of an integral number x, simply follow this algorithm:
initialize s with the empty string
m = x % b
x = x / b
Convert m into a digit, d.
Append d on s.
If x is not zero, goto step 2.
Reverse s
Step 4 is easy if b <= 10 and your computer uses a character encoding where the digits 0-9 are contiguous, because then it's simply d = '0' + m. Otherwise, you need a lookup table.
Steps 5 and 7 can be simplified to append d on the left of s if you know ahead of time how much space you will need and start from the right end in the string.
In the case of b == 2 (e.g. binary representation), step 2 can be simplified to m = x & 1, and step 3 can be simplified to x = x >> 1.
Solution with reverse:
#include <string>
#include <algorithm>
std::string binary(unsigned x)
{
std::string s;
do
{
s.push_back('0' + (x & 1));
} while (x >>= 1);
std::reverse(s.begin(), s.end());
return s;
}
Solution without reverse:
#include <string>
std::string binary(unsigned x)
{
// Warning: this breaks for numbers with more than 64 bits
char buffer[64];
char* p = buffer + 64;
do
{
*--p = '0' + (x & 1);
} while (x >>= 1);
return std::string(p, buffer + 64);
}
AND the number with 100000..., then 010000..., 0010000..., etc. Each time, if the result is 0, put a '0' in a char array, otherwise put a '1'.
int numberOfBits = sizeof(int) * 8;
char binary[numberOfBits + 1];
int decimal = 29;
for(int i = 0; i < numberOfBits; ++i) {
if ((decimal & (0x80000000 >> i)) == 0) {
binary[i] = '0';
} else {
binary[i] = '1';
}
}
binary[numberOfBits] = '\0';
string binaryString(binary);
http://www.phanderson.com/printer/bin_disp.html is a good example.
The basic principle of a simple approach:
Loop until the # is 0
& (bitwise and) the # with 1. Print the result (1 or 0) to the end of string buffer.
Shift the # by 1 bit using >>=.
Repeat loop
Print reversed string buffer
To avoid reversing the string or needing to limit yourself to #s fitting the buffer string length, you can:
Compute ceiling(log2(N)) - say L
Compute mask = 2^L
Loop until mask == 0:
& (bitwise and) the mask with the #. Print the result (1 or 0).
number &= (mask-1)
mask >>= 1 (divide by 2)
I assume this is related to your other question on extensible hashing.
First define some mnemonics for your bits:
const int FIRST_BIT = 0x1;
const int SECOND_BIT = 0x2;
const int THIRD_BIT = 0x4;
Then you have your number you want to convert to a bit string:
int x = someValue;
You can check if a bit is set by using the logical & operator.
if(x & FIRST_BIT)
{
// The first bit is set.
}
And you can keep an std::string and you add 1 to that string if a bit is set, and you add 0 if the bit is not set. Depending on what order you want the string in you can start with the last bit and move to the first or just first to last.
You can refactor this into a loop and using it for arbitrarily sized numbers by calculating the mnemonic bits above using current_bit_value<<=1 after each iteration.
There isn't a direct function, you can just walk along the bits of the int (hint see >> ) and insert a '1' or '0' in the string.
Sounds like a standard interview / homework type question
Use sprintf function to store the formatted output in the string variable, instead of printf for directly printing. Note, however, that these functions only work with C strings, and not C++ strings.
There's a small header only library you can use for this here.
Example:
std::cout << ConvertInteger<Uint32>::ToBinaryString(21);
// Displays "10101"
auto x = ConvertInteger<Int8>::ToBinaryString(21, true);
std::cout << x << "\n"; // displays "00010101"
auto x = ConvertInteger<Uint8>::ToBinaryString(21, true, "0b");
std::cout << x << "\n"; // displays "0b00010101"
Solution without reverse, no additional copy, and with 0-padding:
#include <iostream>
#include <string>
template <short WIDTH>
std::string binary( unsigned x )
{
std::string buffer( WIDTH, '0' );
char *p = &buffer[ WIDTH ];
do {
--p;
if (x & 1) *p = '1';
}
while (x >>= 1);
return buffer;
}
int main()
{
std::cout << "'" << binary<32>(0xf0f0f0f0) << "'" << std::endl;
return 0;
}
This is my best implementation of converting integers(any type) to a std::string. You can remove the template if you are only going to use it for a single integer type. To the best of my knowledge , I think there is a good balance between safety of C++ and cryptic nature of C. Make sure to include the needed headers.
template<typename T>
std::string bstring(T n){
std::string s;
for(int m = sizeof(n) * 8;m--;){
s.push_back('0'+((n >> m) & 1));
}
return s;
}
Use it like so,
std::cout << bstring<size_t>(371) << '\n';
This is the output in my computer(it differs on every computer),
0000000000000000000000000000000000000000000000000000000101110011
Note that the entire binary string is copied and thus the padded zeros which helps to represent the bit size. So the length of the string is the size of size_t in bits.
Lets try a signed integer(negative number),
std::cout << bstring<signed int>(-1) << '\n';
This is the output in my computer(as stated , it differs on every computer),
11111111111111111111111111111111
Note that now the string is smaller , this proves that signed int consumes less space than size_t. As you can see my computer uses the 2's complement method to represent signed integers (negative numbers). You can now see why unsigned short(-1) > signed int(1)
Here is a version made just for signed integers to make this function without templates , i.e use this if you only intend to convert signed integers to string.
std::string bstring(int n){
std::string s;
for(int m = sizeof(n) * 8;m--;){
s.push_back('0'+((n >> m) & 1));
}
return s;
}