Formatting Commas into a long long integer - c++

this is my first time posting a question. I was hoping to get some help on a very old computer science assignment that I never got around to finishing. I'm no longer taking the class, just want to see how to solve this.
Read in an integer (any valid 64-bit
integer = long long type) and output the same number but with commas inserted.
If the user entered -1234567890, your program should output -1,234,567,890. Commas
should appear after every three significant digits (provided more digits remain) starting
from the decimal point and working left toward more significant digits. If the number
entered does not require commas, do not add any. For example, if the input is 234 you
should output 234. The input 0 should produce output 0. Note in the example above
that the number can be positive or negative. Your output must maintain the case of the
input.
I'm relatively new to programming, and this was all I could come up with:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long n;
cout << "Enter an integer:" << endl;
cin >> n;
int ones = n % 10;
int tens = n / 10 % 10;
int hund = n / 100 % 10;
int thous = n / 1000 % 10;
int tthous = n / 10000 % 10;
cout << tthous << thous << "," << hund << tens << ones << endl;
return 0;
}
The original assignment prohibited the use of strings, arrays, and vectors, so please refrain from giving suggestions/solutions that involve these.
I'm aware that some sort of for-loop would probably be required to properly insert the commas in the necessary places, but I just do not know how to go about implementing this.
Thank you in advance to anyone who offers their help!

Just to give you an idea how to solve this, I've maiden a simple implementation. Just keep in mind that is just a simple example:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long n = -1234567890;
if ( n < 0 )
cout << '-';
n = abs(n);
for (long long i = 1000000000000; i > 0; i /= 1000) {
if ( n / i <= 0 ) continue;
cout << n / i ;
n = n - ( n / i) * i;
if ( n > 0 )
cout << ',';
}
return 0;
}
http://coliru.stacked-crooked.com/a/150f75db89c46e99

The easy solution would be to use ios::imbue to set a locale that would do all the work for you:
std::cout.imbue(std::locale(""));
std::cout << n << std::endl;
However, if the restraints don't allow for strings or vectors I doubt that this would be a valid solution. Instead you could use recursion:
void print(long long n, int counter) {
if (n > 0) {
print(n / 10, ++counter);
if (counter % 3 == 0) {
std::cout << ",";
}
std::cout << n%10;
}
}
void print(long long n) {
if (n < 0) {
std::cout << "-";
n *= -1;
}
print(n, 0);
}
And then in the main simply call print(n);

A small template class comma_sep may be a solution, the usage may be as simple as:
cout << comma_sep<long long>(7497592752850).sep() << endl;
Which outputs:
7,497,592,752,850
Picked from here:
https://github.com/arloan/libimsux/blob/main/comma_sep.hxx
template <class I = int, int maxdigits = 32>
class comma_sep
char buff[maxdigits + maxdigits / 3 + 2];
char * p;
I i;
char sc;
public:
comma_sep(I i, char c = ',') : p(buff), i(i), sc(c) {
if (i < 0) {
buff[0] = '-';
*++p = '\0';
}
}
const char * sep() {
return _sep(std::abs(i));
}
private:
const char * _sep(I i) {
I r = i % 1000;
I n = i / 1000;
if (n > 0) {
_sep(n);
p += sprintf(p, "%c%03d", sc, (int)r);
*p = '\0';
} else {
p += sprintf(p, "%d", (int)r);
*p = '\0';
}
return buff;
}
};
The above class handles only integeral numbers, float/double numbers need to use a partial specialized version:
template<int maxd>
class comma_sep<double, maxd> {
comma_sep<int64_t, maxd> _cs;
char fs[64];
double f;
public:
const int max_frac = 12;
comma_sep(double d, char c = ',') : _cs((int64_t)d, c) {
double np;
f = std::abs(modf(d, &np));
}
const char * sep(int frac = 3) {
if (frac < 1 || frac > max_frac) {
throw std::invalid_argument("factional part too too long or invalid");
}
auto p = _cs.sep();
strcpy(fs, p);
char fmt[8], tmp[max_frac+3];
sprintf(fmt, "%%.%dlf", frac);
sprintf(tmp, fmt, f);
return strcat(fs, tmp + 1);
}
};
The two above classes can be improved by adding type-traits like std::is_integral and/or std::is_floating_point, though.

Related

c++ Receiving “-nan.(ind)” from output instead of a number?

#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
double* cal1(double* all1)
{
int t,count=0;
ifstream srcFile("in.txt", ios::in);
if (!srcFile)
{
cout << "error opening source file." << endl;
return 0;
}
char x;
while (srcFile >> x)
{
t = x - 'a' ;
count++;
if (t >= 0 && t <= 25)
all1[t]++;
else
all1[26]++;
}
all1[27] =count ;
srcFile.close();
/* for (t = 0; t <= 26; t++)
{
cout << all1[t] / all1[27]<<endl;
}
cout << all1[27] << endl;*/
return all1;
}
double finalcal1(double* all)
{
int t;
double p,cal1=0;
for (t = 0; t <= 26; t++)
{
p = (all[t] / all[27]);
all[t] = p * log(p);
}
for (t = 0; t <= 26; t++)
{
cal1 -= all[t];
}
return cal1;
}
int main()
{
double *all =new double[28]; //1
double t;
all = cal1(all);
t = finalcal1(all);
cout << t << endl;
delete[] all;
return 0;
}
enter code here
instead of receiving a number from the result, I just got a “-nan.(ind)” which is not even a number. Besides, when I change the number from mark 1 to *all =new double[27] which is what it supposed to be, there would be error or bugs showing up.
double *all =new double[28];
You probably want to initialise all these values to zero to start with since, otherwise, they'll have arbitrary values.
And, if those arbitrary values consist of any NaN items, that will propagate when you add things to them, or divide by some count.
Something like this will do the trick:
double *all = new double[28]();
You may also want to consider the possibility that log(x) is not actually defined for all values of x (such as zero or negative values) - that may be another way in which you could get a NaN.

Large factorial series

I have to print series :-
n*(n-1),n*(n-1)*(n-2),n*(n-1)*(n-2)*(n-3),n*(n-1)*(n-2)*(n-3)*(n-4)...,n!.
Problem is large value of n , it can go upto 37 and n! will obviously go out of bounds ?
I just cant get started , please help , how would you have tackled situation if you were in my place ?
It depends on the language you are using. Some languages automatically switch to a large integer package when numbers get too large for the machine's native integer representation. In other languages, just use a large integer library, which should handle 37! easily.
Wikipedia has a list of arbitrary-precision arithmetic libraries for some languages. There are also lots of other resources on the web.
3 year old problem looked fun.
Simple create a routine to "multiply" a string by a factor. Not highly efficient, yet gets the job done.
#include <stdlib.h>
#include <string.h>
void mult_array(char *x, unsigned factor) {
unsigned accumulator = 0;
size_t n = strlen(x);
size_t i = n;
while (i > 0) {
i--;
accumulator += (unsigned)(x[i]-'0')*factor;
x[i] = (char) (accumulator%10 + '0');
accumulator /= 10;
}
while (accumulator > 0) {
memmove(x+1, x, ++n);
x[i] = (char) (accumulator%10 + '0');
accumulator /= 10;
}
}
#include <stdio.h>
void AS_Factorial(unsigned n) {
char buf[1000]; // Right-size buffer (problem for another day)
sprintf(buf, "%u", n);
fputs(buf, stdout);
while (n>1) {
n--;
mult_array(buf, n);
printf(",%s", buf);
}
puts("");
}
Sample usage and output
int main(void) {
AS_Factorial(5);
AS_Factorial(37);
return 0;
}
5,20,60,120,120
37,1332,46620,1585080,52307640,1673844480,...,13763753091226345046315979581580902400000000
I have just tried BigInteger in Java and it works.
Working code for demonstration purpose:
import java.math.BigInteger;
public class Factorial {
public static int[] primes = {2,3,5,7,11,13,17,19,23,29,31,37};
public static BigInteger computeFactorial(int n) {
if (n==0) {
return new BigInteger(String.valueOf(1));
} else {
return new BigInteger(String.valueOf(n)).multiply(computeFactorial(n-1));
}
}
public static String getPowers(int n){
BigInteger input = computeFactorial(n);
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < primes.length && input.intValue() != 1;) {
BigInteger[] result = input.divideAndRemainder(new BigInteger(String.valueOf(primes[i])));
if (result[1].intValue() == 0) {
input = input.divide(new BigInteger(String.valueOf(primes[i])));
count++;
if (input.intValue() == 1) {sb.append(primes[i] + "(" + count + ") ");}
} else {
if (count!=0)
sb.append(primes[i] + "(" + count + ") ");
count = 0;
i++;
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(getPowers(37));
}
}
Feel free to use it without worrying about copyright if you want.
Update: I didn't realize you were using C++ until now. In that case, you can give boost BigInteger a try.
You may use big integer, but however this still has some limitations, but even though, this datatype can handle a very large value. The value that the big integer can hold, ranges from
-9223372036854775808 to 9223372036854775807 for the signed big integer, and
0 to 18446744073709551615 for the unsigned big integer.
If you really plan to do some bigger value computation which is bigger than the big integer data type, why not try the GMP library?
As from what the site says, "GMP is a free library for arbitrary precision arithmetic, operating on signed integers, rational numbers, and floating point numbers. There is no practical limit to the precision except the ones implied by the available memory in the machine GMP runs on. GMP has a rich set of functions, and the functions have a regular interface." - gmplib.org
You could implement your own big-integer type if it's not permitted to use any thirdparty libraries. You can do something like that:
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
const int base = 1000 * 1000 * 1000; // base value, should be the power of 10
const int lbase = 9; // lg(base)
void output_biginteger(vector<int>& a) {
cout << a.back();
for (int i = (int)a.size() - 2; i >= 0; --i)
cout << setw(lbase) << setfill('0') << a[i];
cout << endl;
}
void multiply_biginteger_by_integer(vector<int>& a, int b) {
int carry = 0;
for (int i = 0; i < (int)a.size(); ++i) {
long long cur = (long long)a[i] * b + carry;
carry = cur / base;
a[i] = cur % base;
}
if (carry > 0) {
a.push_back(carry);
}
}
int main() {
int n = 37; // input your n here
vector<int> current(1, n);
for (int i = n - 1; n >= 1; --n) {
multiply_biginteger_by_integer(current, i);
output_biginteger(current);
}
return 0;
}

Using pow() for large number

I am trying to solve a problem, a part of which requires me to calculate (2^n)%1000000007 , where n<=10^9. But my following code gives me output "0" even for input like n=99.
Is there anyway other than having a loop which multilplies the output by 2 every time and finding the modulo every time (this is not I am looking for as this will be very slow for large numbers).
#include<stdio.h>
#include<math.h>
#include<iostream>
using namespace std;
int main()
{
unsigned long long gaps,total;
while(1)
{
cin>>gaps;
total=(unsigned long long)powf(2,gaps)%1000000007;
cout<<total<<endl;
}
}
You need a "big num" library, it is not clear what platform you are on, but start here:
http://gmplib.org/
this is not I am looking for as this will be very slow for large numbers
Using a bigint library will be considerably slower pretty much any other solution.
Don't take the modulo every pass through the loop: rather, only take it when the output grows bigger than the modulus, as follows:
#include <iostream>
int main() {
int modulus = 1000000007;
int n = 88888888;
long res = 1;
for(long i=0; i < n; ++i) {
res *= 2;
if(res > modulus)
res %= modulus;
}
std::cout << res << std::endl;
}
This is actually pretty quick:
$ time ./t
./t 1.19s user 0.00s system 99% cpu 1.197 total
I should mention that the reason this works is that if a and b are equivalent mod m (that is, a % m = b % m), then this equality holds multiple k of a and b (that is, the foregoing equality implies (a*k)%m = (b*k)%m).
Chris proposed GMP, but if you need just that and want to do things The C++ Way, not The C Way, and without unnecessary complexity, you may just want to check this out - it generates few warnings when compiling, but is quite simple and Just Works™.
You can split your 2^n into chunks of 2^m. You need to find: `
2^m * 2^m * ... 2^(less than m)
Number m should be 31 is for 32-bit CPU. Then your answer is:
chunk1 % k * chunk2 * k ... where k=1000000007
You are still O(N). But then you can utilize the fact that all chunk % k are equal except last one and you can make it O(1)
I wrote this function. It is very inefficient but it works with very large numbers. It uses my self-made algorithm to store big numbers in arrays using a decimal like system.
mpfr2.cpp
#include "mpfr2.h"
void mpfr2::mpfr::setNumber(std::string a) {
for (int i = a.length() - 1, j = 0; i >= 0; ++j, --i) {
_a[j] = a[i] - '0';
}
res_size = a.length();
}
int mpfr2::mpfr::multiply(mpfr& a, mpfr b)
{
mpfr ans = mpfr();
// One by one multiply n with individual digits of res[]
int i = 0;
for (i = 0; i < b.res_size; ++i)
{
for (int j = 0; j < a.res_size; ++j) {
ans._a[i + j] += b._a[i] * a._a[j];
}
}
for (i = 0; i < a.res_size + b.res_size; i++)
{
int tmp = ans._a[i] / 10;
ans._a[i] = ans._a[i] % 10;
ans._a[i + 1] = ans._a[i + 1] + tmp;
}
for (i = a.res_size + b.res_size; i >= 0; i--)
{
if (ans._a[i] > 0) break;
}
ans.res_size = i+1;
a = ans;
return a.res_size;
}
mpfr2::mpfr mpfr2::mpfr::pow(mpfr a, mpfr b) {
mpfr t = a;
std::string bStr = "";
for (int i = b.res_size - 1; i >= 0; --i) {
bStr += std::to_string(b._a[i]);
}
int i = 1;
while (!0) {
if (bStr == std::to_string(i)) break;
a.res_size = multiply(a, t);
// Debugging
std::cout << "\npow() iteration " << i << std::endl;
++i;
}
return a;
}
mpfr2.h
#pragma once
//#infdef MPFR2_H
//#define MPFR2_H
// C standard includes
#include <iostream>
#include <string>
#define MAX 0x7fffffff/32/4 // 2147483647
namespace mpfr2 {
class mpfr
{
public:
int _a[MAX];
int res_size;
void setNumber(std::string);
static int multiply(mpfr&, mpfr);
static mpfr pow(mpfr, mpfr);
};
}
//#endif
main.cpp
#include <iostream>
#include <fstream>
// Local headers
#include "mpfr2.h" // Defines local mpfr algorithm library
// Namespaces
namespace m = mpfr2; // Reduce the typing a bit later...
m::mpfr tetration(m::mpfr, int);
int main() {
// Hardcoded tests
int x = 7;
std::ofstream f("out.txt");
m::mpfr t;
for(int b=1; b<x;b++) {
std::cout << "2^^" << b << std::endl; // Hardcoded message
t.setNumber("2");
m::mpfr res = tetration(t, b);
for (int i = res.res_size - 1; i >= 0; i--) {
std::cout << res._a[i];
f << res._a[i];
}
f << std::endl << std::endl;
std::cout << std::endl << std::endl;
}
char c; std::cin.ignore(); std::cin >> c;
return 0;
}
m::mpfr tetration(m::mpfr a, int b)
{
m::mpfr tmp = a;
if (b <= 0) return m::mpfr();
for (; b > 1; b--) tmp = m::mpfr::pow(a, tmp);
return tmp;
}
I created this for tetration and eventually hyperoperations. When the numbers get really big it can take ages to calculate and a lot of memory. The #define MAX 0x7fffffff/32/4 is the number of decimals one number can have. I might make another algorithm later to combine multiple of these arrays into one number. On my system the max array length is 0x7fffffff aka 2147486347 aka 2^31-1 aka int32_max (which is usually the standard int size) so I had to divide int32_max by 32 to make the creation of this array possible. I also divided it by 4 to reduce memory usage in the multiply() function.
- Jubiman

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

How to check if the binary representation of an integer is a palindrome?

How to check if the binary representation of an integer is a palindrome?
Hopefully correct:
_Bool is_palindrome(unsigned n)
{
unsigned m = 0;
for(unsigned tmp = n; tmp; tmp >>= 1)
m = (m << 1) | (tmp & 1);
return m == n;
}
Since you haven't specified a language in which to do it, here's some C code (not the most efficient implementation, but it should illustrate the point):
/* flip n */
unsigned int flip(unsigned int n)
{
int i, newInt = 0;
for (i=0; i<WORDSIZE; ++i)
{
newInt += (n & 0x0001);
newInt <<= 1;
n >>= 1;
}
return newInt;
}
bool isPalindrome(int n)
{
int flipped = flip(n);
/* shift to remove trailing zeroes */
while (!(flipped & 0x0001))
flipped >>= 1;
return n == flipped;
}
EDIT fixed for your 10001 thing.
Create a 256 lines chart containing a char and it's bit reversed char.
given a 4 byte integer,
take the first char, look it on the chart, compare the answer to the last char of the integer.
if they differ it is not palindrome, if the are the same repeat with the middle chars.
if they differ it is not palindrome else it is.
Plenty of nice solutions here. Let me add one that is not the most efficient, but very readable, in my opinion:
/* Reverses the digits of num assuming the given base. */
uint64_t
reverse_base(uint64_t num, uint8_t base)
{
uint64_t rev = num % base;
for (; num /= base; rev = rev * base + num % base);
return rev;
}
/* Tells whether num is palindrome in the given base. */
bool
is_palindrome_base(uint64_t num, uint8_t base)
{
/* A palindrome is equal to its reverse. */
return num == reverse_base(num, base);
}
/* Tells whether num is a binary palindrome. */
bool
is_palindrome_bin(uint64_t num)
{
/* A binary palindrome is a palindrome in base 2. */
return is_palindrome_base(num, 2);
}
The following should be adaptable to any unsigned type. (Bit operations on signed types tend to be fraught with problems.)
bool test_pal(unsigned n)
{
unsigned t = 0;
for(unsigned bit = 1; bit && bit <= n; bit <<= 1)
t = (t << 1) | !!(n & bit);
return t == n;
}
int palidrome (int num)
{
int rev = 0;
num = number;
while (num != 0)
{
rev = (rev << 1) | (num & 1); num >> 1;
}
if (rev = number) return 1; else return 0;
}
I always have a palindrome function that works with Strings, that returns true if it is, false otherwise, e.g. in Java. The only thing I need to do is something like:
int number = 245;
String test = Integer.toString(number, 2);
if(isPalindrome(test)){
...
}
A generic version:
#include <iostream>
#include <limits>
using namespace std;
template <class T>
bool ispalindrome(T x) {
size_t f = 0, l = (CHAR_BIT * sizeof x) - 1;
// strip leading zeros
while (!(x & (1 << l))) l--;
for (; f != l; ++f, --l) {
bool left = (x & (1 << f)) > 0;
bool right = (x & (1 << l)) > 0;
//cout << left << '\n';
//cout << right << '\n';
if (left != right) break;
}
return f != l;
}
int main() {
cout << ispalindrome(17) << "\n";
}
I think the best approach is to start at the ends and work your way inward, i.e. compare the first bit and the last bit, the second bit and the second to last bit, etc, which will have O(N/2) where N is the size of the int. If at any point your pairs aren't the same, it isn't a palindrome.
bool IsPalindrome(int n) {
bool palindrome = true;
size_t len = sizeof(n) * 8;
for (int i = 0; i < len / 2; i++) {
bool left_bit = !!(n & (1 << len - i - 1));
bool right_bit = !!(n & (1 << i));
if (left_bit != right_bit) {
palindrome = false;
break;
}
}
return palindrome;
}
Sometimes it's good to report a failure too;
There are lots of great answers here about the obvious way to do it, by analyzing in some form or other the bit pattern. I got to wondering, though, if there were any mathematical solutions? Are there properties of palendromic numbers that we might take advantage of?
So I played with the math a little bit, but the answer should really have been obvious from the start. It's trivial to prove that all binary palindromic numbers must be either odd or zero. That's about as far as I was able to get with it.
A little research showed no such approach for decimal palindromes, so it's either a very difficult problem or not solvable via a formal system. It might be interesting to prove the latter...
public static bool IsPalindrome(int n) {
for (int i = 0; i < 16; i++) {
if (((n >> i) & 1) != ((n >> (31 - i)) & 1)) {
return false;
}
}
return true;
}
bool PaLInt (unsigned int i, unsigned int bits)
{
unsigned int t = i;
unsigned int x = 0;
while(i)
{
x = x << bits;
x = x | (i & ((1<<bits) - 1));
i = i >> bits;
}
return x == t;
}
Call PalInt(i,1) for binary pallindromes
Call PalInt(i,3) for Octal Palindromes
Call PalInt(i,4) for Hex Palindromes
I know that this question has been posted 2 years ago, but I have a better solution which doesn't depend on the word size and all,
int temp = 0;
int i = num;
while (1)
{ // let's say num is the number which has to be checked
if (i & 0x1)
{
temp = temp + 1;
}
i = i >> 1;
if (i) {
temp = temp << 1;
}
else
{
break;
}
}
return temp == num;
In JAVA there is an easy way if you understand basic binary airthmetic, here is the code:
public static void main(String []args){
Integer num=73;
String bin=getBinary(num);
String revBin=reverse(bin);
Integer revNum=getInteger(revBin);
System.out.println("Is Palindrome: "+((num^revNum)==0));
}
static String getBinary(int c){
return Integer.toBinaryString(c);
}
static Integer getInteger(String c){
return Integer.parseInt(c,2);
}
static String reverse(String c){
return new StringBuilder(c).reverse().toString();
}
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
unsigned int n = 134217729;
unsigned int bits = floor(log(n)/log(2)+1);
cout<< "Number of bits:" << bits << endl;
unsigned int i=0;
bool isPal = true;
while(i<(bits/2))
{
if(((n & (unsigned int)pow(2,bits-i-1)) && (n & (unsigned int)pow(2,i)))
||
(!(n & (unsigned int)pow(2,bits-i-1)) && !(n & (unsigned int)pow(2,i))))
{
i++;
continue;
}
else
{
cout<<"Not a palindrome" << endl;
isPal = false;
break;
}
}
if(isPal)
cout<<"Number is binary palindrome" << endl;
}
The solution below works in python:
def CheckBinPal(b):
b=str(bin(b))
if b[2:]==b[:1:-1]:
return True
else:
return False
where b is the integer
If you're using Clang, you can make use of some __builtins.
bool binaryPalindrome(const uint32_t n) {
return n == __builtin_bitreverse32(n << __builtin_clz(n));
}
One thing to note is that __builtin_clz(0) is undefined so you'll need to check for zero. If you're compiling on ARM using Clang (next generation mac), then this makes use of the assembly instructions for reverse and clz (compiler explorer).
clz w8, w0
lsl w8, w0, w8
rbit w8, w8
cmp w8, w0
cset w0, eq
ret
x86 has instructions for clz (sort of) but not reversing. Still, Clang will emit the fastest code possible for reversing on the target architecture.
Javascript Solution
function isPalindrome(num) {
const binaryNum = num.toString(2);
console.log(binaryNum)
for(let i=0, j=binaryNum.length-1; i<=j; i++, j--) {
if(binaryNum[i]!==binaryNum[j]) return false;
}
return true;
}
console.log(isPalindrome(0))