The most efficient way to reverse a number - c++

I am looking for an efficient algorithm to reverse a number, e.g.
Input: 3456789
Output: 9876543
In C++ there are plenty of options with shifting and bit masks but what would be the most efficient way ?
My platform: x86_64
Numbers range: XXX - XXXXXXXXXX (3 - 9 digits)
EDIT
Last digit of my input will never be a zero so there is no leading zeros problem.

Something like this will work:
#include <iostream>
int main()
{
long in = 3456789;
long out = 0;
while(in)
{
out *= 10;
out += in % 10;
in /= 10;
}
std::cout << out << std::endl;
return 0;
}

#include <stdio.h>
unsigned int reverse(unsigned int val)
{
unsigned int retval = 0;
while( val > 0)
{
retval = 10*retval + val%10;
val /= 10;
}
printf("returning - %d", retval);
return retval;
}
int main()
{
reverse(123);
}

You may convert the number to string and then reverse the string with STL algorithms. Code below should work:
long number = 123456789;
stringstream ss;
ss << number;
string numberToStr = ss.str();
std::reverse(numberToStr.begin(), numberToStr.end());
cout << atol(numberToStr.c_str());
You may need to include those relevant header files. I am not sure whether it is the most efficient way, but STL algorithms are generally very efficient.

static public int getReverseInt(int value) {
int resultNumber = 0;
for (int i = value; i != 0;) {
int d = i / 10;
resultNumber = (resultNumber - d) * 10 + i;
i = d;
}
return resultNumber;
}
I think this will be the fastest possible method without using asm. Note that d*10 + i is equivalent to i%10 but much faster since modulo is around 10 times slower than multiplication.
I tested it and it is about 25 % faster than other answers.

int ans=0;
int rev(int n)
{
ans=(ans+(n%10))*10; // using recursive function to reverse a number;
if(n>9)
rev(n/10);
}
int main()
{
int m=rev(456123); // m=32
return 0;
}

//Recursive method to find the reverse of a number
#include <bits/stdc++.h>
using namespace std;
int reversDigits(int num)
{
static int rev_num = 0;
static int base_pos = 1;
if(num > 0)
{
reversDigits(num/10);
rev_num += (num%10)*base_pos;
base_pos *= 10;
}
return rev_num;
}
int main()
{
int num = 4562;
cout << "Reverse " << reversDigits(num);
} ``

// recursive method to reverse number. lang = java
static void reverseNumber(int number){
// number == 0 is the base case
if(number !=0 ){
//recursive case
System.out.print(number %10);
reverseNumber(number /10);
}
}

This solution is not as efficient but it does solve the problem and can be useful.
It returns long long for any signed integer(int, long, long long, etc) and unsigned long long for any unsigned integer (unsigned int, unsigned long, unsigned long long, etc).
The char type depends of compiler implementation can be signed or unsigned.
#include <iostream>
#include <string>
#include <algorithm>
template <bool B>
struct SignedNumber
{
};
template <>
struct SignedNumber<true>
{
typedef long long type;
};
template <>
struct SignedNumber<false>
{
typedef unsigned long long type;
};
template <typename TNumber = int,
typename TResult = typename SignedNumber<std::is_signed<TNumber>::value>::type,
typename = typename std::void_t<std::enable_if_t<std::numeric_limits<TNumber>::is_integer>>>
TResult ReverseNumber(TNumber value)
{
bool isSigned = std::is_signed_v<TNumber>;
int sign = 1;
if (value < 0)
{
value *= -1;
sign = -1;
}
std::string str = std::to_string(value);
std::reverse(str.begin(), str.end());
return isSigned ? std::stoll(str) * sign : std::stoull(str) * sign;
}
int main()
{
std::cout << ReverseNumber(true) << std::endl; //bool -> unsigned long long
std::cout << ReverseNumber(false) << std::endl; //bool -> unsigned long long
std::cout << ReverseNumber('#') << std::endl; //char -> long long or unsigned long long
std::cout << ReverseNumber(46) << std::endl; //int -> long long
std::cout << ReverseNumber(-46) << std::endl; //int -> long long
std::cout << ReverseNumber(46U) << std::endl; //unsigned int -> unsigned long long
std::cout << ReverseNumber(46L) << std::endl; //long -> long long
std::cout << ReverseNumber(-46LL) << std::endl; //long long -> long long
std::cout << ReverseNumber(46UL) << std::endl; //unsigned long -> unsigned long long
std::cout << ReverseNumber(4600ULL) << std::endl; //unsigned long long -> unsigned long long
}
Output
1
0
64
64
-64
64
64
-64
64
64
Test this code
https://repl.it/#JomaCorpFX/IntegerToStr#main.cpp

If it is 32-bit unsigned integer (987,654,321 being max input) and if you have 4GB free memory(by efficiency, did you mean memory too?),
result=table[value]; // index 12345 has 54321, index 123 has 321
should be fast enough. Assuming memory is accessed at 100 ns time or 200 cycles and integer is 7 digits on average, other solutions have these:
7 multiplications,
7 adds,
7 modulo,
7 divisions,
7 loop iterations with 7 comparisons
if these make more than 100 nanoseconds / 200 cycles, then table would be faster. For example, 1 integer division can be as high as 40 cycles, so I guess this can be fast enough. If inputs are repeated, then data will coming from cache will have even less latency.
But if there are millions of reversing operations in parallel, then computing by CPU is absolutely the better choice (probably 30x-100x speedup using vectorized compute loop + multithreading) than accessing table. It has multiple pipelines per core and multiple cores. You can even choose CUDA/OpenCL with a GPU for extra throughput and this reversing solution from other answers look like perfectly embarrassingly parallelizable since 1 input computes independently of other inputs.

This is the easiest one:
#include<iostream>
using namespace std;
int main()
{
int number, reversed=0;
cout<<"Input a number to Reverse: ";
cin>>number;
while(number!=0)
{
reversed= reversed*10;
reversed=reversed+number%10;
number=number/10;
}
cout<<"Reversed number is: "<<reversed<<endl;
}

Related

code to find the value of nCr shows the answer to some values as 0( Ex:30 15)

The following is the code:
#include
using namespace std;
int factorial(int num){
unsigned long long int fact=1;
for (int i = num; i >=1; i--)
{
fact=fact*i;
}
return fact;
}
int main()
{
unsigned long long int n,r,value;
cout<<"Enter a number whose nCr value is to be calculated (n and r respectively): ";
cin>>n>>r;
unsigned long long int a=factorial(n);
unsigned long long int b=factorial(r);
unsigned long long int c=factorial(n-r);
value=a/(b*c);
cout<<"The value of nCr is : "<<value;
return 0;
}
Why do I get the answer to some of the inputs like (30 15),(30 12), etc as 0.
30! is a very large 33-digit number, so that's overflowing the int variable your program is trying to store it in. If you print it out, you'll see the actual value that gets stored in a is smaller than the value of b*c in the denominator of the final computation, so value=a/(b*c); gets truncated to 0 by integer division.
Even if you return the result of factorial as an unsigned long long int the result of 30! will overflow, since it can only store 64 bits (and that's compiler dependent).
#include "stdafx.h"
#include <iostream>
unsigned long long int factorial(int num) {
unsigned long long int fact = 1;
for (int i = num; i >= 1; i--)
{
fact = fact * i;
}
return fact;
}
int main()
{
unsigned long long int n, r, value;
std::cout << "Enter a number whose nCr value is to be calculated (n and r respectively): ";
std::cin >> n >> r;
unsigned long long int a = factorial(n);
std::cout << "n! = " << a << std::endl;
unsigned long long int b = factorial(r);
std::cout << "r! = " << b << std::endl;
unsigned long long int c = factorial(n - r);
std::cout << "(n-r)! = " << c << std::endl;
std::cout << "r!(n-r)! = " << b*c << std::endl;
value = a / (b*c);
std::cout << "The value of nCr is : " << value << std::endl;
system("pause");
return 0;
}
Output:
Enter a number whose nCr value is to be calculated (n and r respectively): 30 12
n! = 9682165104862298112
r! = 479001600
(n-r)! = 6402373705728000
r!(n-r)! = 12940075575627743232
The value of nCr is : 0
Press any key to continue . . .
The main issue with your code is return type of factorial Method it should be same as the return type of "fact".
Second issue with code is that it cannot handle huge number above i.e, max value of unsigned long long int "18,446,744,073,709,551,615"(https://www.tutorialspoint.com/cplusplus/cpp_data_types.htm).
So just change the data types of variables fact,a,b,c and factorial method to "long double" which can accomodate 12 bytes of data.
Code below is just modified for tracing purpose... you can skip the line which you don't need. Be careful with data types. Code is modified as per your requirement for huge calculations.
Please reply if you have any confusion. And up-vote my answer if it looks right to you.
You can remove std:: from the code if not need by your compiler.
#include <iostream>
long double factorial(int num){
long double fact=1;
for (int i = num; i >=1; i--)
{
fact=fact*i;
}
return fact;
}
int main()
{
unsigned long long int n=0,r=0;
long double value=0;
std::cout<<"Enter a number whose nCr value is to be calculated (n and r respectively): ";
std::cin>>n>>r;
std::cout<<n;
std::cout<<r;
long double a=factorial(n);
long double b=factorial(r);
long double c=factorial(n-r);
std::cout<<"\na="<<a;
std::cout<<"\nb="<<b;
std::cout<<"\nc="<<c;
long double d = b*c;
std::cout<<"\nd="<<d;
value=(unsigned long long int)(a/d);
std::cout<<"\nThe value of nCr is : "<<value;
return 0;
`enter code here`}

Incorrect addition in a Function

I am writing a function in C++ to convert a number from some base to decimal.
It works fine when the number of digits is even, but when it is odd it gives wrong answer.
For example:
Number to convert : 100
Base to convert to: 10
Correct answer : 100
Function's output : 99
Here is the code:
unsigned long long convertToDecimal(const std::string& number, const unsigned base)
{
std::string characters = "0123456789abcdef";
unsigned long long res = 0;
for(int i = 0, len = number.size(); i<len; ++i)
{
res += characters.find(number.at(i))*std::pow(base, len-1-i);
}
return res;
}
I'm using g++ C++11.
I can't reproduce your particular issue, but std::pow returns a floating point number and your implementation may have introduced some sort of rounding error which leaded to a wrong result when converted to unsigned long long.
To avoid those errors, when dealing with integer numbers, you should consider to avoid std::pow at all. Your function, for example, could have been written like this:
#include <iostream>
#include <string>
#include <cmath>
unsigned long long convertToDecimal(const std::string& number, const unsigned base)
{
std::string characters = "0123456789abcdef";
unsigned long long res = 0;
unsigned long long power = 1;
for(auto i = number.crbegin(); i != number.crend(); ++i)
{
// As in your code, I'm not checking for erroneous input
res += characters.find(*i) * power;
power *= base;
}
return res;
}
int main ()
{
std::cout << convertToDecimal("100", 2) << '\n'; // --> 4
std::cout << convertToDecimal("1234", 8) << '\n'; // --> 668
std::cout << convertToDecimal("99999", 10) << '\n'; // --> 99999
std::cout << convertToDecimal("fedcba", 16) << '\n'; // --> 16702650
}

C++ - how to find the length of an integer

I'm trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use of classes from the STL, although the program spec does say we can use "common C libraries" (gonna ask my professor if I can use cmath, because I'm assuming log10(num) + 1 is the easiest way, but I was wondering if there was another way).
Ah, and this doesn't have to handle negative numbers. Solely non-negative numbers.
I'm attempting to create a variant "MyInt" class that can handle a wider range of values using a dynamic array. Any tips would be appreciated! Thanks!
Not necessarily the most efficient, but one of the shortest and most readable using C++:
std::to_string(num).length()
The number of digits of an integer n in any base is trivially obtained by dividing until you're done:
unsigned int number_of_digits = 0;
do {
++number_of_digits;
n /= base;
} while (n);
There is a much better way to do it
#include<cmath>
...
int size = trunc(log10(num)) + 1
....
works for int and decimal
If you can use C libraries then one method would be to use sprintf, e.g.
#include <cstdio>
char s[32];
int len = sprintf(s, "%d", i);
"I mean the number of digits in an integer, i.e. "123" has a length of 3"
int i = 123;
// the "length" of 0 is 1:
int len = 1;
// and for numbers greater than 0:
if (i > 0) {
// we count how many times it can be divided by 10:
// (how many times we can cut off the last digit until we end up with 0)
for (len = 0; i > 0; len++) {
i = i / 10;
}
}
// and that's our "length":
std::cout << len;
outputs 3
Closed formula for the longest int (I used int here, but works for any signed integral type):
1 + (int) ceil((8*sizeof(int)-1) * log10(2))
Explanation:
sizeof(int) // number bytes in int
8*sizeof(int) // number of binary digits (bits)
8*sizeof(int)-1 // discount one bit for the negatives
(8*sizeof(int)-1) * log10(2) // convert to decimal, because:
// 1 bit == log10(2) decimal digits
(int) ceil((8*sizeof(int)-1) * log10(2)) // round up to whole digits
1 + (int) ceil((8*sizeof(int)-1) * log10(2)) // make room for the minus sign
For an int type of 4 bytes, the result is 11. An example of 4 bytes int with 11 decimal digits is: "-2147483648".
If you want the number of decimal digits of some int value, you can use the following function:
unsigned base10_size(int value)
{
if(value == 0) {
return 1u;
}
unsigned ret;
double dval;
if(value > 0) {
ret = 0;
dval = value;
} else {
// Make room for the minus sign, and proceed as if positive.
ret = 1;
dval = -double(value);
}
ret += ceil(log10(dval+1.0));
return ret;
}
I tested this function for the whole range of int in g++ 9.3.0 for x86-64.
int intLength(int i) {
int l=0;
for(;i;i/=10) l++;
return l==0 ? 1 : l;
}
Here's a tiny efficient one
Being a computer nerd and not a maths nerd I'd do:
char buffer[64];
int len = sprintf(buffer, "%d", theNum);
Would this be an efficient approach? Converting to a string and finding the length property?
int num = 123
string strNum = to_string(num); // 123 becomes "123"
int length = strNum.length(); // length = 3
char array[3]; // or whatever you want to do with the length
How about (works also for 0 and negatives):
int digits( int x ) {
return ( (bool) x * (int) log10( abs( x ) ) + 1 );
}
Best way is to find using log, it works always
int len = ceil(log10(num))+1;
Code for finding Length of int and decimal number:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int len,num;
cin >> num;
len = log10(num) + 1;
cout << len << endl;
return 0;
}
//sample input output
/*45566
5
Process returned 0 (0x0) execution time : 3.292 s
Press any key to continue.
*/
There are no inbuilt functions in C/C++ nor in STL for finding length of integer but there are few ways by which it can found
Here is a sample C++ code to find the length of an integer, it can be written in a function for reuse.
#include<iostream>
using namespace std;
int main()
{
long long int n;
cin>>n;
unsigned long int integer_length = 0;
while(n>0)
{
integer_length++;
n = n/10;
}
cout<<integer_length<<endl;
return 0;
}
Here is another way, convert the integer to string and find the length, it accomplishes same with a single line:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
long long int n;
cin>>n;
unsigned long int integer_length = 0;
// convert to string
integer_length = to_string(n).length();
cout<<integer_length<<endl;
return 0;
}
Note: Do include the cstring header file
The easiest way to use without any libraries in c++ is
#include <iostream>
using namespace std;
int main()
{
int num, length = 0;
cin >> num;
while(num){
num /= 10;
length++;
}
cout << length;
}
You can also use this function:
int countlength(int number)
{
static int count = 0;
if (number > 0)
{
count++;
number /= 10;
countlength(number);
}
return count;
}
#include <math.h>
int intLen(int num)
{
if (num == 0 || num == 1)
return 1;
else if(num < 0)
return ceil(log10(num * -1))+1;
else
return ceil(log10(num));
}
Most efficient code to find length of a number.. counts zeros as well, note "n" is the number to be given.
#include <iostream>
using namespace std;
int main()
{
int n,len= 0;
cin>>n;
while(n!=0)
{
len++;
n=n/10;
}
cout<<len<<endl;
return 0;
}

Converting an array of 2 digit numbers into an integer (C++)

Is it possible to take an array filled with 2 digit numbers e.g.
[10,11,12,13,...]
and multiply each element in the list by 100^(position in the array) and sum the result so that:
mysteryFunction[10,11,12] //The function performs 10*100^0 + 11*100^1 + 12*100^3
= 121110
and also
mysteryFunction[10,11,12,13]
= 13121110
when I do not know the number of elements in the array?
(yes, the reverse of order is intended but not 100% necessary, and just in case you missed it the first time the numbers will always be 2 digits)
Just for a bit of background to the problem: this is to try to improve my attempt at an RSA encryption program, at the moment I am multiplying each member of the array by 100^(the position of the number) written out each time which means that each word which I use to encrypt must be a certain length.
For example to encrypt "ab" I have converted it to an array [10,11] but need to convert it to 1110 before I can put it through the RSA algorithm. I would need to adjust my code for if I then wanted to use a three letter word, again for a four letter word etc. which I'm sure you will agree is not ideal. My code is nothing like industry standard but I am happy to upload it should anyone want to see it (I have also already managed this in Haskell if anyone would like to see that). I thought that the background information was necessary just so that I don't get hundreds of downvotes from people thinking that I'm trying to trick them into doing homework for me. Thank you very much for any help, I really do appreciate it!
EDIT: Thank you for all of the answers! They perfectly answer the question that I asked but I am having problems incorporating them into my current program, if I post my code so far would you be able to help? When I tried to include the answer provided I got an error message (I can't vote up because I don't have enough reputation, sorry that I haven't accepted any answers yet).
#include <iostream>
#include <string>
#include <math.h>
int returnVal (char x)
{
return (int) x;
}
unsigned long long modExp(unsigned long long b, unsigned long long e, unsigned long long m)
{
unsigned long long remainder;
int x = 1;
while (e != 0)
{
remainder = e % 2;
e= e/2;
if (remainder == 1)
x = (x * b) % m;
b= (b * b) % m;
}
return x;
}
int main()
{
unsigned long long p = 80001;
unsigned long long q = 70021;
int e = 7;
unsigned long long n = p * q;
std::string foo = "ab";
for (int i = 0; i < foo.length(); i++);
{
std::cout << modExp (returnVal((foo[0]) - 87) + returnVal (foo[1] -87) * 100, e, n);
}
}
If you want to use plain C-style arrays, you will have to separately know the number of entries. With this approach, your mysterious function might be defined like this:
unsigned mysteryFunction(unsigned numbers[], size_t n)
{
unsigned result = 0;
unsigned factor = 1;
for (size_t i = 0; i < n; ++i)
{
result += factor * numbers[i];
factor *= 100;
}
return result;
}
You can test this code with the following:
#include <iostream>
int main()
{
unsigned ar[] = {10, 11, 12, 13};
std::cout << mysteryFunction(ar, 4) << "\n";
return 0;
}
On the other hand, if you want to utilize the STL's vector class, you won't separately need the size. The code itself won't need too many changes.
Also note that the built-in integer types cannot handle very large numbers, so you might want to look into an arbitrary precision number library, like GMP.
EDIT: Here's a version of the function which accepts a std::string and uses the characters' ASCII values minus 87 as the numbers:
unsigned mysteryFunction(const std::string& input)
{
unsigned result = 0;
unsigned factor = 1;
for (size_t i = 0; i < input.size(); ++i)
{
result += factor * (input[i] - 87);
factor *= 100;
}
return result;
}
The test code becomes:
#include <iostream>
#include <string>
int main()
{
std::string myString = "abcde";
std::cout << mysteryFunction(myString) << "\n";
return 0;
}
The program prints: 1413121110
As benedek mentioned, here's an implementation using dynamic arrays via std::vector.
unsigned mystery(std::vector<unsigned> vect)
{
unsigned result = 0;
unsigned factor = 1;
for (auto& item : vect)
{
result += factor * item;
factor *= 100;
}
return result;
}
void main(void)
{
std::vector<unsigned> ar;
ar.push_back(10);
ar.push_back(11);
ar.push_back(12);
ar.push_back(13);
std::cout << mystery(ar);
}
I would like to suggest the following solutions.
You could use standard algorithm std::accumulate declared in header <numeric>
For example
#include <iostream>
#include <numeric>
int main()
{
unsigned int a[] = { 10, 11, 12, 13 };
unsigned long long i = 1;
unsigned long long s =
std::accumulate( std::begin( a ), std::end( a ), 0ull,
[&]( unsigned long long acc, unsigned int x )
{
return ( acc += x * i, i *= 100, acc );
} );
std::cout << "s = " << s << std::endl;
return 0;
}
The output is
s = 13121110
The same can be done with using the range based for statement
#include <iostream>
#include <numeric>
int main()
{
unsigned int a[] = { 10, 11, 12, 13 };
unsigned long long i = 1;
unsigned long long s = 0;
for ( unsigned int x : a )
{
s += x * i; i *= 100;
}
std::cout << "s = " << s << std::endl;
return 0;
}
You could also write a separate function
unsigned long long mysteryFunction( const unsigned int a[], size_t n )
{
unsigned long long s = 0;
unsigned long long i = 1;
for ( size_t k = 0; k < n; k++ )
{
s += a[k] * i; i *= 100;
}
return s;
}
Also think about using std::string instead of integral numbers to keep an encrypted result.

Using long and arrays in C++

I've been working on a program that converts numbers into binary. As you can see my program here, I've written so that it can scale for larger numbers then a traditional binary code, such as 2 lines (16-bits) for numbers bigger then 255. However, going larger requires long instead of int, but that doesn't seem to be playing well, producing output such as this. Would anyone mind helping me change the program to use long? Or would it require a fundamental change in the code instead of some minor edits?
#include <iostream>
#include <math.h>
using namespace std;
int main(int argc, char **argv)
{
int j=0;
int c=8;
long a = 1;
int i=1;
cin >> a;
while (a >= (pow(2,c))) {
c = c+8;
i++;
}
long block[i*8];
for (long tw;tw<(i*8);tw++)
{
block[tw] = 0;
}
j=((i*8)-1);
long b = 0;
while (j != -1)
{
if (b+(pow(2,j))<=a)
{
block[j]=1;
b=b+(pow(2,j));
}
j--;
}
long q=0;
cout << endl;
int y=1;
long z = 0;
for (y;y<=i;y++) {
for (z;z<8;z++) {
cout << block[z+q];
}
cout << endl;
z = 0;
q = q + (8*y);
}
}
You are making your code far more complicated than it needs to be. This will print out a single 32-bit integer in binary:
const unsigned int bit_count = sizeof(int) * 8 - 1;
int a;
std::cin >> a;
for (unsigned int i = bit_count; i > 0; --i)
{
unsigned int t = (1 << i);
std::cout << (a & t ? "1" : "0");
}
std::cout << (a & 1 ? "1" : "0");
std::cout << std::endl;
If you want to block it off by ranges to make it easier to read, you simply need to place range on the loop (or move it to a function that takes a range).
Why not something simple like this? You could store the intermediate bits in an array or a string instead of using cout.
int convert(long n)
{
long k=1;
while(k<n)//find the most significant bit
{
k*=2;
}
if(k>n)//fix the overshoot
{
k/=2;
}
while(k>0)
{
if(int(n/k)%2==0)
{
cout<<0;//find the (next) most
}
else
{
cout<<1;//significant binary digit
}
k/=2;//go to the next column to the right and repeat
}
}
For a bit more flexibly, here's another way to do it with templates. Template instantiations with signed types are omitted intentionally due to extension issues.
template <typename T>
void print_binary(const T input, const short grouping = 4)
{
unsigned int bit_count = sizeof(T) * 8;
T nth_bit = 1 << (bit_count - 1);
for(int i = 0; i < bit_count; i++, nth_bit >>= 1 )
{
cout << (input & nth_bit ? "1" : "0");
if( i % grouping == grouping-1 ) // print binary in groups
cout << ' ';
}
cout << endl;
}
template <>
void print_binary<signed>(const signed input, const short grouping);
template <>
void print_binary<signed short>(const signed short input, const short grouping);
template <>
void print_binary<signed long>(const signed long input, const short grouping);
template <>
void print_binary<signed char>(const signed char input, const short grouping);