For reversing a number in C++ which ends with zeros - c++

I want to write a program for reversing a number. For reversing a number like 2300 to 32 so that the ending zeros are not printed, I found this method:
#include<iostream>
using namespace std;
int main()
{
int l;
cin>>l;
bool leading = true;
while (l>0)
{
if ((l%10==0)&& (leading==true))
{
l /= 10;
leading = false; // prints 032 as output
continue;
}
// leading = false; this prints correct 32
cout<<l%10;
l /= 10;
}
return 0;
}
The instruction of assigning boolean leading false inside the if statement is not giving a valid answer, but I suppose assigning it false should give 32 as output whether we give it outside or inside if statement as its purpose is just to make it false once you get the last digit to be a non zero.
Please tell the reason of difference in outputs.

The reason for the difference in output is because when you make leading = false inside the if statement, you are making it false right after encountering the first zero. When you encounter the remaining zeroes, leading will be false and you will be printing it.
When you make leading = false outside the if statement, you are basically waiting till you encounter all zeroes before making it false.
If you are looking to reverse a number, this is the well known logic to do so:
int reverse(int n)
{
int r; //remainder
int rev = 0; //reversed number
while(n != 0)
{
r = n%10;
rev = rev*10 + r;
n /= 10;
}
return rev;
}
EDIT:
The above code snippet is fine if you just want to understand the logic to reverse a number. But if you want to implement the logic anywhere you have to make sure you handle integer overflow problems (the reversed number could be too big to be stored in an integer!!).
The following code will take care of integer overflow:
int reverse(int n)
{
int r; //remainder
int rev = 0; //reversed number
while(n != 0)
{
r = n%10;
if(INT_MAX/10 < rev)
{
cout << "Reversed number too big for an int.";
break;
}
else if(INT_MAX-r < rev*10)
{
cout << "Reversed number too big for an int.";
break;
}
rev = rev*10 + r;
n /= 10;
}
if(n != 0)
{
//could not reverse number
//take appropriate action
}
return rev;
}

First, rewrite without continue to make the flow clearer,
while (l > 0)
{
if ((l % 10 == 0) && (leading == true))
{
l /= 10;
leading = false; // prints 032 as output
}
else
{
// leading = false; this prints correct 32
cout << l % 10;
l /= 10;
}
}
and move the division common to both branches out of the conditional,
while (l > 0)
{
if ((l % 10 == 0) && (leading == true))
{
leading = false; // prints 032 as output
}
else
{
// leading = false; this prints correct 32
cout << l % 10;
}
l /= 10;
}
and now you see that the only difference between the two is the condition under which the assignment leading = false happens.
The correct version says, "If this digit is non-zero or a non-leading zero, remember that the next digit is not a leading zero, and print this digit. Then divide."
Your broken version says, "If this is a leading zero, the next digit is not a leading zero." which is pretty obviously not the case.

Just try this ,
#include <iostream>
using namespace std;
int main() {
int n, reversedNumber = 0, remainder;
cout << "Enter an integer: ";
cin >> n;
while(n != 0) {
remainder = n%10;
reversedNumber = reversedNumber*10 + remainder;
n /= 10;
}
cout << "Reversed Number = " << reversedNumber;
return 0;
}
Working for me...

When reversing digits of numbers or generally when working with digits and the actual
value does not matter then treating the number as an array of digits is simpler than working with the whole int. How to treat a number as an array of digits conveniently? std::string:
#include <iostream>
#include <string>
#include <sstream>
int reverse_number(int x) {
std::string xs = std::to_string(x);
std::string revx{ xs.rbegin(),xs.rend()};
std::stringstream ss{revx};
int result;
ss >> result;
return result;
}
int main() {
std::cout << reverse_number(123) << "\n";
std::cout << reverse_number(1230) << "\n";
}
std::to_string converts the int to a std::string. std::string revx{ xs.rbegin(),xs.rend()}; constructs the reversed string by using reverse iterators, and eventually a stringstream can be used to parse the number. Output of the above is:
321
321

Related

How can I find prime reversed numbers?

I have to write a program to check if the entered number has these qualifications:
A number that is prime it self, the reverse of that number is also prime, and the number's digits are prime numbers too (Like this number: 7523).
If the needs meet, it has to show "yes" when you enter and run the program otherwise "no".
I know both codes for prime and reverse numbers but I don't know how to merge them.
This is the code:
#include <iostream>
#include <conio.h>
using namespace std;
void prime_check(int x) {
int a, i, flag = 1;
cin >> a;
for (i = 2; i <= a / 2 && flag == 1; i++) {
if (a % i == 0)
flag = 0;
}
if (flag == 1)
cout << "prime";
else
break;
}
int main() {
int a, r, sum = 0;
cin >> a;
while (a != 0) {
r = a % 10;
sum = (sum * 10) + r;
a = a / 10;
}
}
The program has to check each digit of the number entered to see if it is prime or not in every step, then show "yes", but it doesn't work.
Welcome to the site.
I don't know how to merge them.
void prime_check(int n) { /*code*/ }
I'd understand that you don't know how to use this.
It's very easy!
int main()
{
int i = 0;
prime_check(i);
}
If you are confused about how the program executes, you could use a debugger to see where it goes. But since using a debugger can be a bit hard at first, I would suggest to add debug prints to see how the program executes.
This line of code prints the file and line number automatically.
std::cout << __FILE__ << ":" << __LINE__ << "\n";
I'd suggest to add it at the start of every function you wish to understand.
One step further is to make it into a macro, just so that it's easy to use.
#define DEBUGPRINT std::cout << __FILE__ << ":" << __LINE__ << "\n";
Check a working example here:
http://www.cpp.sh/2hpam
Note that it says <stdin>::14 instead of the filename because it's running on a webpage.
I have done some changes to your code, and added comments everywhere I've made changes. Check it out:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0, original; // added original variable, to store the number added
bool eachDigit = true; // added to keep track of each digit
cin >> a;
original = a;
while (a != 0) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && prime_check(original) && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
For optimization, you can check if the entered number is prime or not before starting that loop, and also you can break the loop right away if one of the digits of the entered number is not prime, Like this:
#include <iostream>
#include <conio.h>
using namespace std;
bool prime_check(int x) { // I have changed the datatype of this function to bool, because I want to store if all the digits are prime or not
int i, flag = 1; // Removed the variable a, because the function is already taking x as input
for (i = 2; i <= x / 2 && flag == 1; i++) {
if (x % i == 0)
flag = 0;
}
return flag == 1;
}
int main() {
int a, r, sum = 0;
bool eachDigit = true, entered; // added to keep track of each digit
cin >> a;
entered = prime_check(a);
while (a != 0 && entered && eachDigit) {
r = a % 10;
eachDigit = prime_check(r); // Here Each digit of entered number is checked for prime
sum = (sum * 10) + r;
a = a / 10;
}
if (eachDigit && entered && prime_check(sum)) // At the end checking if all the digits, entered number and the revered number are prime
cout << "yes";
else
cout<< "no";
}
Suppose you have an int variable num which you want to check for your conditions, you can achieve your target by the following:
int rev_num = 0;
bool flag = true; // Assuming 'num' satisfies your conditions, until proven otherwise
if (prime_check(num) == false) {
flag = false;
}
else while (num != 0) {
int digit = num % 10;
rev_num = rev_num * 10 + digit;
// Assuming your prime_check function returns 'true' and 'false'
if (prime_check(digit) == false) {
flag = false;
break;
}
num /= 10;
}
if (prime_check(rev_num) == false) {
flag = false;
}
if (flag) {
cout << "Number satisfies all conditions\n";
}
else {
cout << "Number does not satisfy all conditions\n";
}
The problem is that each of your functions is doing three things, 1) inputting the number, 2) testing the number and 3) outputting the result. To combine these functions you need to have two functions that are only testing the number. Then you can use both functions on the same number, instead of inputting two different numbers and printing two different results. You will need to use function parameters, to pass the input number to the two functions, and function return values to return the result of the test. The inputting of the number and the outputting of the result go in main. Here's an outline
// returns true if the number is a prime, false otherwise
bool prime_check(int a)
{
...
}
// returns true if the number is a reverse prime, false otherwise
bool reverse_prime_check(int a)
{
...
}
int main()
{
int a;
cin >> a;
if (prime_check(a) && reverse_prime_check(a))
cout << "prime\n";
else
cout << "not prime\n";
}
I'll leave you to write the functions themselves, and there's nothing here to do the digit checks either. I'll leave you do to that.

Using recursion to reverse an integer without trailing 0's in C++

I am stuck on how to omit trailing zeros, on a recursive call to reverse an integer. If you could just guide me to the right path I'd appreciate it. I am stuck and do not know how to do it. I have came this far, but am struggling to complete it. Thanks.
int main() {
int numToReverse;
cout << "Please enter in a number: " << endl;
cin >> numToReverse;
cout << reverseIntRecursion(numToReverse) << endl;
}
int reverseIntRecursion(int n) {
if (n < 10) //Base Case
return n;
else
cout << n % 10; // Prints out the last number
return reverseIntRecursion(n / 10); // General Case, Recursive Function
}
Maybe easiest way is parse int to string (array of chars) and print as array?
Here is some code that works just fine as long as you enter true for the second parameter:
int ReverseIntRecursion(int, bool);
int main(int argc, const char * argv[]) {
std::cout << ReverseIntRecursion(30400, true);
std::cout << std::endl;
return 0;
}
int ReverseIntRecursion(int N, bool FirstIter)
{
if (N < 10)
return N;
else if (N % 10 == 0 && FirstIter)
return ReverseIntRecursion(N/10, true);
else
std::cout << (N % 10);
return ReverseIntRecursion(N/10, false);
}
// prints 403
Your function isn't reversing an integer. It just prints digits in a reverse order.
This is why you are getting your trailing zeros problem. If you wrote a function which actually reversed the integer - your problem would disappear.
For example:
// Helper function for reversing an integer.
int reverseIntRecursionBase(int n, int& base) {
if (n < 10) // trivial case. If n consists of a single digit - reversed n is equal to n.
{
return n;
}
int result = reverseIntRecursionBase (n/10, base); // recurse until you hit a trivial case.
/*
The leftmost digits in the original number should be the
rightmost digits in the reversed number.
This code will be first executed, after trivial case has been hit:
e.g. given number 1234, this line will be first reached when n = 12; result = 1.
*/
base *= 10;
result = (n % 10)*base + result;
return result;
}
int reverseIntRecursion(int n) {
int base = 1;
return reverseIntRecursionBase (n, base);
}
Live demo.

C++ Program abruptly ends after cin

I am writing code to get the last digit of very large fibonacci numbers such as fib(239), etc.. I am using strings to store the numbers, grabbing the individual chars from end to beginning and then converting them to int and than storing the values back into another string. I have not been able to test what I have written because my program keeps abruptly closing after the std::cin >> n; line.
Here is what I have so far.
#include <iostream>
#include <string>
using std::cin;
using std::cout;
using namespace std;
char get_fibonacci_last_digit_naive(int n) {
cout << "in func";
if (n <= 1)
return (char)n;
string previous= "0";
string current= "1";
for (int i = 0; i < n - 1; ++i) {
//long long tmp_previous = previous;
string tmp_previous= previous;
previous = current;
//current = tmp_previous + current; // could also use previous instead of current
// for with the current length of the longest of the two strings
//iterates from the end of the string to the front
for (int j=current.length(); j>=0; --j) {
// grab consectutive positions in the strings & convert them to integers
int t;
if (tmp_previous.at(j) == '\0')
// tmp_previous is empty use 0 instead
t=0;
else
t = stoi((string&)(tmp_previous.at(j)));
int c = stoi((string&)(current.at(j)));
// add the integers together
int valueAtJ= t+c;
// store the value into the equivalent position in current
current.at(j) = (char)(valueAtJ);
}
cout << current << ":current value";
}
return current[current.length()-1];
}
int main() {
int n;
std::cin >> n;
//char& c = get_fibonacci_last_digit_naive(n); // reference to a local variable returned WARNING
// http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable
cout << "before call";
char c = get_fibonacci_last_digit_naive(n);
std::cout << c << '\n';
return 0;
}
The output is consistently the same. No matter what I enter for n, the output is always the same. This is the line I used to run the code and its output.
$ g++ -pipe -O2 -std=c++14 fibonacci_last_digit.cpp -lm
$ ./a.exe
10
There is a newline after the 10 and the 10 is what I input for n.
I appreciate any help. And happy holidays!
I'm posting this because your understanding of the problem seems to be taking a backseat to the choice of solution you're attempting to deploy. This is an example of an XY Problem, a problem where the choice of solution method and problems or roadblocks with its implementation obfuscates the actual problem you're trying to solve.
You are trying to calculate the final digit of the Nth Fibonacci number, where N could be gregarious. The basic understanding of the fibonacci sequence tells you that
fib(0) = 0
fib(1) = 1
fib(n) = fib(n-1) + fib(n-2), for all n larger than 1.
The iterative solution to solving fib(N) for its value would be:
unsigned fib(unsigned n)
{
if (n <= 1)
return n;
unsigned previous = 0;
unsigned current = 1;
for (int i=1; i<n; ++i)
{
unsigned value = previous + current;
previous = current;
current = value;
}
return current;
}
which is all well and good, but will obviously overflow once N causes an overflow of the storage capabilities of our chosen data type (in the above case, unsigned on most 32bit platforms will overflow after a mere 47 iterations).
But we don't need the actual fib values for each iteration. We only need the last digit of each iteration. Well, the base-10 last-digit is easy enough to get from any unsigned value. For our example, simply replace this:
current = value;
with this:
current = value % 10;
giving us a near-identical algorithm, but one that only "remembers" the last digit on each iteration:
unsigned fib_last_digit(unsigned n)
{
if (n <= 1)
return n;
unsigned previous = 0;
unsigned current = 1;
for (int i=1; i<n; ++i)
{
unsigned value = previous + current;
previous = current;
current = value % 10; // HERE
}
return current;
}
Now current always holds the single last digit of the prior sum, whether that prior sum exceeded 10 or not really isn't relevant to us. Once we have that the next iteration can use it to calculate the sum of two single positive digits, which cannot exceed 18, and again, we only need the last digit from that for the next iteration, etc.. This continues until we iterate however many times requested, and when finished, the final answer will present itself.
Validation
We know the first 20 or so fibonacci numbers look like this, run through fib:
0:0
1:1
2:1
3:2
4:3
5:5
6:8
7:13
8:21
9:34
10:55
11:89
12:144
13:233
14:377
15:610
16:987
17:1597
18:2584
19:4181
20:6765
Here's what we get when we run the algorithm through fib_last_digit instead:
0:0
1:1
2:1
3:2
4:3
5:5
6:8
7:3
8:1
9:4
10:5
11:9
12:4
13:3
14:7
15:0
16:7
17:7
18:4
19:1
20:5
That should give you a budding sense of confidence this is likely the algorithm you seek, and you can forego the string manipulations entirely.
Running this code on a Mac I get:
libc++abi.dylib: terminating with uncaught exception of type std::out_of_range: basic_string before callin funcAbort trap: 6
The most obvious problem with the code itself is in the following line:
for (int j=current.length(); j>=0; --j) {
Reasons:
If you are doing things like current.at(j), this will crash immediately. For example, the string "blah" has length 4, but there is no character at position 4.
The length of tmp_previous may be different from current. Calling tmp_previous.at(j) will crash when you go from 8 to 13 for example.
Additionally, as others have pointed out, if the the only thing you're interested in is the last digit, you do not need to go through the trouble of looping through every digit of every number. The trick here is to only remember the last digit of previous and current, so large numbers are never a problem and you don't have to do things like stoi.
As an alternative to a previous answer would be the string addition.
I tested it with the fibonacci number of 100000 and it works fine in just a few seconds. Working only with the last digit solves your problem for even larger numbers for sure. for all of you requiring the fibonacci number as well, here an algorithm:
std::string str_add(std::string a, std::string b)
{
// http://ideone.com/o7wLTt
size_t n = max(a.size(), b.size());
if (n > a.size()) {
a = string(n-a.size(), '0') + a;
}
if (n > b.size()) {
b = string(n-b.size(), '0') + b;
}
string result(n + 1, '0');
char carry = 0;
std::transform(a.rbegin(), a.rend(), b.rbegin(), result.rbegin(), [&carry](char x, char y)
{
char z = (x - '0') + (y - '0') + carry;
if (z > 9) {
carry = 1;
z -= 10;
} else {
carry = 0;
}
return z + '0';
});
result[0] = carry + '0';
n = result.find_first_not_of("0");
if (n != string::npos) {
result = result.substr(n);
}
return result;
}
std::string str_fib(size_t i)
{
std::string n1 = "0";
std::string n2 = "1";
for (size_t idx = 0; idx < i; ++idx) {
const std::string f = str_add(n1, n2);
n1 = n2;
n2 = f;
}
return n1;
}
int main() {
const size_t i = 100000;
const std::string f = str_fib(i);
if (!f.empty()) {
std::cout << "fibonacci of " << i << " = " << f << " | last digit: " << f[f.size() - 1] << std::endl;
}
std::cin.sync(); std::cin.get();
return 0;
}
Try it with first calculating the fibonacci number and then converting the int to a std::string using std::to_string(). in the following you can extract the last digit using the [] operator on the last index.
int fib(int i)
{
int number = 1;
if (i > 2) {
number = fib(i - 1) + fib(i - 2);
}
return number;
}
int main() {
const int i = 10;
const int f = fib(i);
const std::string s = std::to_string(f);
if (!s.empty()) {
std::cout << "fibonacci of " << i << " = " << f << " | last digit: " << s[s.size() - 1] << std::endl;
}
std::cin.sync(); std::cin.get();
return 0;
}
Avoid duplicates of the using keyword using.
Also consider switching from int to long or long long when your numbers get bigger. Since the fibonacci numbers are positive, also use unsigned.

How to reverse a negative integer recursively in C++?

I am working on some recursion practice and I need to write a program that reverse the input of an integer
Example of input : cin >> 12345; The output should be 54321
but if that integer is negative the negative sign needs to be appended to only the first number.
Example of input : cin >> -1234; output -4321
I am having a hard time getting my program to adapt to the negative numbers. The way I have it set up if I run
Example of test : 12345 I get the right output 54321
So my recursion and base are successful. But if I run a negative I get
Example of test : -12345 I get this for a reason I don't understand -5-4-3-2 1
#include<iostream>
using namespace std;
void reverse(int);
int main()
{
int num;
cout << "Input a number : ";
cin >> num;
reverse(num);
return 0;
}
void reverse(int in)
{
bool negative = false;
if (in < 0)
{
in = 0 - in;
negative = true;
}
if (in / 10 == 0)
cout << in % 10;
else{
if (negative == true)
in = 0 - in;
cout << in % 10;
reverse(in / 10);
}
}
To reverse a negative number, you output a - and then reverse the corresponding positive number. I'd suggest using recursion rather than state, like this:
void reverse(int in)
{
if (in < 0)
{
cout << '-';
reverse(-in);
}
else
{
// code to recursively reverse non-negative numbers here
}
}
Split the reverse function into two parts: the first part just prints - (if the input is negative) and then calls the second part, which is the recursive code you have. (You don't need any of the if (negative) ... handling any more, since the first part already handled it.)
Incidentally, if (bool_variable == true) ... is overly verbose. It's easier to read code if you say something like if (value_is_negative) ....
Your recursive function doesn't hold state. When you recurse the first time, it prints the '-' symbol but every time you send back a negative number to the recursion, it runs as if it is the first time and prints '-' again.
It's better to print '-' first time you see a negative number and send the rest of the number as a positive value to the recursion.
#include<iostream>
using namespace std;
void reverse(int);
int main()
{
int num;
cout << "Input a number : ";
cin >> num;
reverse(num);
return 0;
}
void reverse(int in)
{
bool negative = false;
if (in < 0)
{
in = 0 - in;
negative = true;
}
if (in / 10 == 0)
cout << in % 10;
else{
if (negative == true) {
cout << '-';
negative = false;
}
cout << in % 10;
reverse(in / 10);
}
}
int reverse(long int x) {
long int reversedNumber = 0, remainder;
bool isNegative = false;
if (x <0){
isNegative = true;
x *= -1;
}
while(x > 0) {
remainder = x%10;
reversedNumber = reversedNumber*10 + remainder;
x= x/10;
}
if (isNegative) {
if (reversedNumber > INT_MAX){
return 0;
}
else
return reversedNumber*(-1);
}
else
{
if (reversedNumber > INT_MAX){
return 0;
}
else
return reversedNumber;
}
}

C++ - Decimal to binary converting

I wrote a 'simple' (it took me 30 minutes) program that converts decimal number to binary. I am SURE that there's a lot simpler way so can you show me?
Here's the code:
#include <iostream>
#include <stdlib.h>
using namespace std;
int a1, a2, remainder;
int tab = 0;
int maxtab = 0;
int table[0];
int main()
{
system("clear");
cout << "Enter a decimal number: ";
cin >> a1;
a2 = a1; //we need our number for later on so we save it in another variable
while (a1!=0) //dividing by two until we hit 0
{
remainder = a1%2; //getting a remainder - decimal number(1 or 0)
a1 = a1/2; //dividing our number by two
maxtab++; //+1 to max elements of the table
}
maxtab--; //-1 to max elements of the table (when dividing finishes it adds 1 additional elemnt that we don't want and it's equal to 0)
a1 = a2; //we must do calculations one more time so we're gatting back our original number
table[0] = table[maxtab]; //we set the number of elements in our table to maxtab (we don't get 10's of 0's)
while (a1!=0) //same calculations 2nd time but adding every 1 or 0 (remainder) to separate element in table
{
remainder = a1%2; //getting a remainder
a1 = a1/2; //dividing by 2
table[tab] = remainder; //adding 0 or 1 to an element
tab++; //tab (element count) increases by 1 so next remainder is saved in another element
}
tab--; //same as with maxtab--
cout << "Your binary number: ";
while (tab>=0) //until we get to the 0 (1st) element of the table
{
cout << table[tab] << " "; //write the value of an element (0 or 1)
tab--; //decreasing by 1 so we show 0's and 1's FROM THE BACK (correct way)
}
cout << endl;
return 0;
}
By the way it's complicated but I tried my best.
edit - Here is the solution I ended up using:
std::string toBinary(int n)
{
std::string r;
while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
return r;
}
std::bitset has a .to_string() method that returns a std::string holding a text representation in binary, with leading-zero padding.
Choose the width of the bitset as needed for your data, e.g. std::bitset<32> to get 32-character strings from 32-bit integers.
#include <iostream>
#include <bitset>
int main()
{
std::string binary = std::bitset<8>(128).to_string(); //to binary
std::cout<<binary<<"\n";
unsigned long decimal = std::bitset<8>(binary).to_ulong();
std::cout<<decimal<<"\n";
return 0;
}
EDIT: Please do not edit my answer for Octal and Hexadecimal. The OP specifically asked for Decimal To Binary.
The following is a recursive function which takes a positive integer and prints its binary digits to the console.
Alex suggested, for efficiency, you may want to remove printf() and store the result in memory... depending on storage method result may be reversed.
/**
* Takes a unsigned integer, converts it into binary and prints it to the console.
* #param n the number to convert and print
*/
void convertToBinary(unsigned int n)
{
if (n / 2 != 0) {
convertToBinary(n / 2);
}
printf("%d", n % 2);
}
Credits to UoA ENGGEN 131
*Note: The benefit of using an unsigned int is that it can't be negative.
You can use std::bitset to convert a number to its binary format.
Use the following code snippet:
std::string binary = std::bitset<8>(n).to_string();
I found this on stackoverflow itself. I am attaching the link.
A pretty straight forward solution to print binary:
#include <iostream>
using namespace std;
int main()
{
int num,arr[64];
cin>>num;
int i=0,r;
while(num!=0)
{
r = num%2;
arr[i++] = r;
num /= 2;
}
for(int j=i-1;j>=0;j--){
cout<<arr[j];
}
}
Non recursive solution:
#include <iostream>
#include<string>
std::string toBinary(int n)
{
std::string r;
while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;}
return r;
}
int main()
{
std::string i= toBinary(10);
std::cout<<i;
}
Recursive solution:
#include <iostream>
#include<string>
std::string r="";
std::string toBinary(int n)
{
r=(n%2==0 ?"0":"1")+r;
if (n / 2 != 0) {
toBinary(n / 2);
}
return r;
}
int main()
{
std::string i=toBinary(10);
std::cout<<i;
}
An int variable is not in decimal, it's in binary. What you're looking for is a binary string representation of the number, which you can get by applying a mask that filters individual bits, and then printing them:
for( int i = sizeof(value)*CHAR_BIT-1; i>=0; --i)
cout << value & (1 << i) ? '1' : '0';
That's the solution if your question is algorithmic. If not, you should use the std::bitset class to handle this for you:
bitset< sizeof(value)*CHAR_BIT > bits( value );
cout << bits.to_string();
Here are two approaches. The one is similar to your approach
#include <iostream>
#include <string>
#include <limits>
#include <algorithm>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
unsigned long long x = 0;
std::cin >> x;
if ( !x ) break;
const unsigned long long base = 2;
std::string s;
s.reserve( std::numeric_limits<unsigned long long>::digits );
do { s.push_back( x % base + '0' ); } while ( x /= base );
std::cout << std::string( s.rbegin(), s.rend() ) << std::endl;
}
}
and the other uses std::bitset as others suggested.
#include <iostream>
#include <string>
#include <bitset>
#include <limits>
int main()
{
while ( true )
{
std::cout << "Enter a non-negative number (0-exit): ";
unsigned long long x = 0;
std::cin >> x;
if ( !x ) break;
std::string s =
std::bitset<std::numeric_limits<unsigned long long>::digits>( x ).to_string();
std::string::size_type n = s.find( '1' );
std::cout << s.substr( n ) << std::endl;
}
}
The conversion from natural number to a binary string:
string toBinary(int n) {
if (n==0) return "0";
else if (n==1) return "1";
else if (n%2 == 0) return toBinary(n/2) + "0";
else if (n%2 != 0) return toBinary(n/2) + "1";
}
For this , In C++ you can use itoa() function .This function convert any Decimal integer to binary, decimal , hexadecimal and octal number.
#include<bits/stdc++.h>
using namespace std;
int main(){
int a;
char res[1000];
cin>>a;
itoa(a,res,10);
cout<<"Decimal- "<<res<<endl;
itoa(a,res,2);
cout<<"Binary- "<<res<<endl;
itoa(a,res,16);
cout<<"Hexadecimal- "<<res<<endl;
itoa(a,res,8);
cout<<"Octal- "<<res<<endl;return 0;
}
However, it is only supported by specific compilers.
You can see also: itoa - C++ Reference
Here is modern variant that can be used for ints of different sizes.
#include <type_traits>
#include <bitset>
template<typename T>
std::enable_if_t<std::is_integral_v<T>,std::string>
encode_binary(T i){
return std::bitset<sizeof(T) * 8>(i).to_string();
}
Your solution needs a modification. The final string should be reversed before returning:
std::reverse(r.begin(), r.end());
return r;
DECIMAL TO BINARY NO ARRAYS USED *made by Oya:
I'm still a beginner, so this code will only use loops and variables xD...
Hope you like it. This can probably be made simpler than it is...
#include <iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int main()
{
int i;
int expoentes; //the sequence > pow(2,i) or 2^i
int decimal;
int extra; //this will be used to add some 0s between the 1s
int x = 1;
cout << "\nThis program converts natural numbers into binary code\nPlease enter a Natural number:";
cout << "\n\nWARNING: Only works until ~1.073 millions\n";
cout << " To exit, enter a negative number\n\n";
while(decimal >= 0){
cout << "\n----- // -----\n\n";
cin >> decimal;
cout << "\n";
if(decimal == 0){
cout << "0";
}
while(decimal >= 1){
i = 0;
expoentes = 1;
while(decimal >= expoentes){
i++;
expoentes = pow(2,i);
}
x = 1;
cout << "1";
decimal -= pow(2,i-x);
extra = pow(2,i-1-x);
while(decimal < extra){
cout << "0";
x++;
extra = pow(2,i-1-x);
}
}
}
return 0;
}
here a simple converter by using std::string as container. it allows a negative value.
#include <iostream>
#include <string>
#include <limits>
int main()
{
int x = -14;
int n = std::numeric_limits<int>::digits - 1;
std::string s;
s.reserve(n + 1);
do
s.push_back(((x >> n) & 1) + '0');
while(--n > -1);
std::cout << s << '\n';
}
This is a more simple program than ever
//Program to convert Decimal into Binary
#include<iostream>
using namespace std;
int main()
{
long int dec;
int rem,i,j,bin[100],count=-1;
again:
cout<<"ENTER THE DECIMAL NUMBER:- ";
cin>>dec;//input of Decimal
if(dec<0)
{
cout<<"PLEASE ENTER A POSITIVE DECIMAL";
goto again;
}
else
{
cout<<"\nIT's BINARY FORM IS:- ";
for(i=0;dec!=0;i++)//making array of binary, but reversed
{
rem=dec%2;
bin[i]=rem;
dec=dec/2;
count++;
}
for(j=count;j>=0;j--)//reversed binary is printed in correct order
{
cout<<bin[j];
}
}
return 0;
}
There is in fact a very simple way to do so. What we do is using a recursive function which is given the number (int) in the parameter. It is pretty easy to understand. You can add other conditions/variations too. Here is the code:
int binary(int num)
{
int rem;
if (num <= 1)
{
cout << num;
return num;
}
rem = num % 2;
binary(num / 2);
cout << rem;
return rem;
}
// function to convert decimal to binary
void decToBinary(int n)
{
// array to store binary number
int binaryNum[1000];
// counter for binary array
int i = 0;
while (n > 0) {
// storing remainder in binary array
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
// printing binary array in reverse order
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
refer :-
https://www.geeksforgeeks.org/program-decimal-binary-conversion/
or
using function :-
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n;cin>>n;
cout<<bitset<8>(n).to_string()<<endl;
}
or
using left shift
#include<bits/stdc++.h>
using namespace std;
int main()
{
// here n is the number of bit representation we want
int n;cin>>n;
// num is a number whose binary representation we want
int num;
cin>>num;
for(int i=n-1;i>=0;i--)
{
if( num & ( 1 << i ) ) cout<<1;
else cout<<0;
}
}
#include <iostream>
#include <bitset>
#define bits(x) (std::string( \
std::bitset<8>(x).to_string<char,std::string::traits_type, std::string::allocator_type>() ).c_str() )
int main() {
std::cout << bits( -86 >> 1 ) << ": " << (-86 >> 1) << std::endl;
return 0;
}
Okay.. I might be a bit new to C++, but I feel the above examples don't quite get the job done right.
Here's my take on this situation.
char* DecimalToBinary(unsigned __int64 value, int bit_precision)
{
int length = (bit_precision + 7) >> 3 << 3;
static char* binary = new char[1 + length];
int begin = length - bit_precision;
unsigned __int64 bit_value = 1;
for (int n = length; --n >= begin; )
{
binary[n] = 48 | ((value & bit_value) == bit_value);
bit_value <<= 1;
}
for (int n = begin; --n >= 0; )
binary[n] = 48;
binary[length] = 0;
return binary;
}
#value = The Value we are checking.
#bit_precision = The highest left most bit to check for.
#Length = The Maximum Byte Block Size. E.g. 7 = 1 Byte and 9 = 2 Byte, but we represent this in form of bits so 1 Byte = 8 Bits.
#binary = just some dumb name I gave to call the array of chars we are setting. We set this to static so it won't be recreated with every call. For simply getting a result and display it then this works good, but if let's say you wanted to display multiple results on a UI they would all show up as the last result. This can be fixed by removing static, but make sure you delete [] the results when you are done with it.
#begin = This is the lowest index that we are checking. Everything beyond this point is ignored. Or as shown in 2nd loop set to 0.
#first loop - Here we set the value to 48 and basically add a 0 or 1 to 48 based on the bool value of (value & bit_value) == bit_value. If this is true the char is set to 49. If this is false the char is set to 48. Then we shift the bit_value or basically multiply it by 2.
#second loop - Here we set all the indexes we ignored to 48 or '0'.
SOME EXAMPLE OUTPUTS!!!
int main()
{
int val = -1;
std::cout << DecimalToBinary(val, 1) << '\n';
std::cout << DecimalToBinary(val, 3) << '\n';
std::cout << DecimalToBinary(val, 7) << '\n';
std::cout << DecimalToBinary(val, 33) << '\n';
std::cout << DecimalToBinary(val, 64) << '\n';
std::cout << "\nPress any key to continue. . .";
std::cin.ignore();
return 0;
}
00000001 //Value = 2^1 - 1
00000111 //Value = 2^3 - 1.
01111111 //Value = 2^7 - 1.
0000000111111111111111111111111111111111 //Value = 2^33 - 1.
1111111111111111111111111111111111111111111111111111111111111111 //Value = 2^64 - 1.
SPEED TESTS
Original Question's Answer: "Method: toBinary(int);"
Executions: 10,000 , Total Time (Milli): 4701.15 , Average Time (Nanoseconds): 470114
My Version: "Method: DecimalToBinary(int, int);"
//Using 64 Bit Precision.
Executions: 10,000,000 , Total Time (Milli): 3386 , Average Time (Nanoseconds): 338
//Using 1 Bit Precision.
Executions: 10,000,000, Total Time (Milli): 634, Average Time (Nanoseconds): 63
Below is simple C code that converts binary to decimal and back again. I wrote it long ago for a project in which the target was an embedded processor and the development tools had a stdlib that was way too big for the firmware ROM.
This is generic C code that does not use any library, nor does it use division or the remainder (%) operator (which is slow on some embedded processors), nor does it use any floating point, nor does it use any table lookup nor emulate any BCD arithmetic. What it does make use of is the type long long, more specifically unsigned long long (or uint64_t), so if your embedded processor (and the C compiler that goes with it) cannot do 64-bit integer arithmetic, this code is not for your application. Otherwise, I think this is production quality C code (maybe after changing long to int32_t and unsigned long long to uint64_t). I have run this overnight to test it for every 2³² signed integer values and there is no error in conversion in either direction.
We had a C compiler/linker that could generate executables and we needed to do what we could do without any stdlib (which was a pig). So no printf() nor scanf(). Not even an sprintf() nor sscanf(). But we still had a user interface and had to convert base-10 numbers into binary and back. (We also made up our own malloc()-like utility also and our own transcendental math functions too.)
So this was how I did it (the main program and calls to stdlib were there for testing this thing on my mac, not for the embedded code). Also, because some older dev systems don't recognize "int64_t" and "uint64_t" and similar types, the types long long and unsigned long long are used and assumed to be the same. And long is assumed to be 32 bits. I guess I could have typedefed it.
// returns an error code, 0 if no error,
// -1 if too big, -2 for other formatting errors
int decimal_to_binary(char *dec, long *bin)
{
int i = 0;
int past_leading_space = 0;
while (i <= 64 && !past_leading_space) // first get past leading spaces
{
if (dec[i] == ' ')
{
i++;
}
else
{
past_leading_space = 1;
}
}
if (!past_leading_space)
{
return -2; // 64 leading spaces does not a number make
}
// at this point the only legitimate remaining
// chars are decimal digits or a leading plus or minus sign
int negative = 0;
if (dec[i] == '-')
{
negative = 1;
i++;
}
else if (dec[i] == '+')
{
i++; // do nothing but go on to next char
}
// now the only legitimate chars are decimal digits
if (dec[i] == '\0')
{
return -2; // there needs to be at least one good
} // digit before terminating string
unsigned long abs_bin = 0;
while (i <= 64 && dec[i] != '\0')
{
if ( dec[i] >= '0' && dec[i] <= '9' )
{
if (abs_bin > 214748364)
{
return -1; // this is going to be too big
}
abs_bin *= 10; // previous value gets bumped to the left one digit...
abs_bin += (unsigned long)(dec[i] - '0'); // ... and a new digit appended to the right
i++;
}
else
{
return -2; // not a legit digit in text string
}
}
if (dec[i] != '\0')
{
return -2; // not terminated string in 64 chars
}
if (negative)
{
if (abs_bin > 2147483648)
{
return -1; // too big
}
*bin = -(long)abs_bin;
}
else
{
if (abs_bin > 2147483647)
{
return -1; // too big
}
*bin = (long)abs_bin;
}
return 0;
}
void binary_to_decimal(char *dec, long bin)
{
unsigned long long acc; // 64-bit unsigned integer
if (bin < 0)
{
*(dec++) = '-'; // leading minus sign
bin = -bin; // make bin value positive
}
acc = 989312855LL*(unsigned long)bin; // very nearly 0.2303423488 * 2^32
acc += 0x00000000FFFFFFFFLL; // we need to round up
acc >>= 32;
acc += 57646075LL*(unsigned long)bin;
// (2^59)/(10^10) = 57646075.2303423488 = 57646075 + (989312854.979825)/(2^32)
int past_leading_zeros = 0;
for (int i=9; i>=0; i--) // maximum number of digits is 10
{
acc <<= 1;
acc += (acc<<2); // an efficient way to multiply a long long by 10
// acc *= 10;
unsigned int digit = (unsigned int)(acc >> 59); // the digit we want is in bits 59 - 62
if (digit > 0)
{
past_leading_zeros = 1;
}
if (past_leading_zeros)
{
*(dec++) = '0' + digit;
}
acc &= 0x07FFFFFFFFFFFFFFLL; // mask off this digit and go on to the next digit
}
if (!past_leading_zeros) // if all digits are zero ...
{
*(dec++) = '0'; // ... put in at least one zero digit
}
*dec = '\0'; // terminate string
}
#if 1
#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
{
char dec[64];
long bin, result1, result2;
unsigned long num_errors;
long long long_long_bin;
num_errors = 0;
for (long_long_bin=-2147483648LL; long_long_bin<=2147483647LL; long_long_bin++)
{
bin = (long)long_long_bin;
if ((bin&0x00FFFFFFL) == 0)
{
printf("bin = %ld \n", bin); // this is to tell us that things are moving along
}
binary_to_decimal(dec, bin);
decimal_to_binary(dec, &result1);
sscanf(dec, "%ld", &result2); // decimal_to_binary() should do the same as this sscanf()
if (bin != result1 || bin != result2)
{
num_errors++;
printf("bin = %ld, result1 = %ld, result2 = %ld, num_errors = %ld, dec = %s \n",
bin, result1, result2, num_errors, dec);
}
}
printf("num_errors = %ld \n", num_errors);
return 0;
}
#else
#include <stdlib.h>
#include <stdio.h>
int main (int argc, const char* argv[])
{
char dec[64];
long bin;
printf("bin = ");
scanf("%ld", &bin);
while (bin != 0)
{
binary_to_decimal(dec, bin);
printf("dec = %s \n", dec);
printf("bin = ");
scanf("%ld", &bin);
}
return 0;
}
#endif
My way of converting decimal to binary in C++. But since we are using mod, this function will work in case of hexadecimal or octal also. You can also specify bits. This function keeps calculating the lowest significant bit and place it on the end of the string. If you are not so similar to this method than you can vist: https://www.wikihow.com/Convert-from-Decimal-to-Binary
#include <bits/stdc++.h>
using namespace std;
string itob(int bits, int n) {
int count;
char str[bits + 1]; // +1 to append NULL character.
str[bits] = '\0'; // The NULL character in a character array flags the end
// of the string, not appending it may cause problems.
count = bits - 1; // If the length of a string is n, than the index of the
// last character of the string will be n - 1. Cause the
// index is 0 based not 1 based. Try yourself.
do {
if (n % 2)
str[count] = '1';
else
str[count] = '0';
n /= 2;
count--;
} while (n > 0);
while (count > -1) {
str[count] = '0';
count--;
}
return str;
}
int main() {
cout << itob(1, 0) << endl; // 0 in 1 bit binary.
cout << itob(2, 1) << endl; // 1 in 2 bit binary.
cout << itob(3, 2) << endl; // 2 in 3 bit binary.
cout << itob(4, 4) << endl; // 4 in 4 bit binary.
cout << itob(5, 15) << endl; // 15 in 5 bit binary.
cout << itob(6, 30) << endl; // 30 in 6 bit binary.
cout << itob(7, 61) << endl; // 61 in 7 bit binary.
cout << itob(8, 127) << endl; // 127 in 8 bit binary.
return 0;
}
The Output:
0
01
010
0100
01111
011110
0111101
01111111
Since you asked for a simple way, I am sharing this answer, after 8 years
Here is the expression!
Is it not interesting when there is no if condition, and we can get 0 or 1 with just a simple expression?
Well yes, NO if, NO long division
Here is what each variable means
Note: variable is the orange highlighted ones
Number: 0-infinity (a value to be converted to binary)
binary holder: 1 / 2 / 4 / 8 / 16 / 32 / ... (Place of binary needed, just like tens, hundreds)
Result: 0 or 1
If you want to make binary holder from 1 / 2 / 4 / 8 / 16 /... to 1 / 2 / 3 / 4 / 5/...
then use this expression
The procedure is simple for the second expression
First, the number variable is always, your number needed, and its stable.
Second the binary holder variable needs to be changed ,in a for loop, by +1 for the second image, x2 for the first image
I don't know c++ a lot ,here is a js code,for your understanding
function FindBinary(Number) {
var x,i,BinaryValue = "",binaryHolder = 1;
for (i = 1; Math.pow(2, i) <= Number; i++) {}//for trimming, you can even remove this and set i to 7,see the result
for (x = 1; x <= i; x++) {
var Algorithm = ((Number - (Number % binaryHolder)) / binaryHolder) % 2;//Main algorithm
BinaryValue = Algorithm + BinaryValue;
binaryHolder += binaryHolder;
}
return BinaryValue;
}
console.log(FindBinary(17));//your number
more ever, I think language doesn't matters a lot for algorithm questions
You want to do something like:
cout << "Enter a decimal number: ";
cin >> a1;
cout << setbase(2);
cout << a1
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
int main() {
// Initialize Variables
double x;
int xOct;
int xHex;
//Initialize a variable that stores the order if the numbers in binary/sexagesimal base
vector<int> rem;
//Get Demical value
cout << "Number (demical base): ";
cin >> x;
//Set the variables
xOct = x;
xHex = x;
//Get the binary value
for (int i = 0; x >= 1; i++) {
rem.push_back(abs(remainder(x, 2)));
x = floor(x / 2);
}
//Print binary value
cout << "Binary: ";
int n = rem.size();
while (n > 0) {
n--;
cout << rem[n];
} cout << endl;
//Print octal base
cout << oct << "Octal: " << xOct << endl;
//Print hexademical base
cout << hex << "Hexademical: " << xHex << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int a,b;
cin>>a;
for(int i=31;i>=0;i--)
{
b=(a>>i)&1;
cout<<b;
}
}
HOPE YOU LIKE THIS SIMPLE CODE OF CONVERSION FROM DECIMAL TO BINARY
#include<iostream>
using namespace std;
int main()
{
int input,rem,res,count=0,i=0;
cout<<"Input number: ";
cin>>input;`enter code here`
int num=input;
while(input > 0)
{
input=input/2;
count++;
}
int arr[count];
while(num > 0)
{
arr[i]=num%2;
num=num/2;
i++;
}
for(int i=count-1 ; i>=0 ; i--)
{
cout<<" " << arr[i]<<" ";
}
return 0;
}
#include <iostream>
// x is our number to test
// pow is a power of 2 (e.g. 128, 64, 32, etc...)
int printandDecrementBit(int x, int pow)
{
// Test whether our x is greater than some power of 2 and print the bit
if (x >= pow)
{
std::cout << "1";
// If x is greater than our power of 2, subtract the power of 2
return x - pow;
}
else
{
std::cout << "0";
return x;
}
}
int main()
{
std::cout << "Enter an integer between 0 and 255: ";
int x;
std::cin >> x;
x = printandDecrementBit(x, 128);
x = printandDecrementBit(x, 64);
x = printandDecrementBit(x, 32);
x = printandDecrementBit(x, 16);
std::cout << " ";
x = printandDecrementBit(x, 8);
x = printandDecrementBit(x, 4);
x = printandDecrementBit(x, 2);
x = printandDecrementBit(x, 1);
return 0;
}
this is a simple way to get the binary form of an int. credit to learncpp.com. im sure this could be used in different ways to get to the same point.
In this approach, the decimal will be converted to the respective binary number in the string formate. The string return type is chosen since it can handle more range of input values.
class Solution {
public:
string ConvertToBinary(int num)
{
vector<int> bin;
string op;
for (int i = 0; num > 0; i++)
{
bin.push_back(num % 2);
num /= 2;
}
reverse(bin.begin(), bin.end());
for (size_t i = 0; i < bin.size(); ++i)
{
op += to_string(bin[i]);
}
return op;
}
};
using bitmask and bitwise and .
string int2bin(int n){
string x;
for(int i=0;i<32;i++){
if(n&1) {x+='1';}
else {x+='0';}
n>>=1;
}
reverse(x.begin(),x.end());
return x;
}
You Could use std::bitset:
#include <bits/stdc++.h>
int main()
{
std::string binary = std::bitset<(int)ceil(log2(10))>(10).to_string(); // decimal number is 10
std::cout << binary << std::endl; // 1010
return 0;
}
SOLUTION 1
Shortest function. Recursive. No headers required.
size_t bin(int i) {return i<2?i:10*bin(i/2)+i%2;}
The simplicity of this function comes at the cost of some limitations. It returns correct values only for arguments between 0 and 1048575 (2 to the power of how many digits the largest unsigned int has, -1). I used the following program to test it:
#include <iostream> // std::cout, std::cin
#include <climits> // ULLONG_MAX
#include <math.h> // pow()
int main()
{
size_t bin(int);
int digits(size_t);
int i = digits(ULLONG_MAX); // maximum digits of the return value of bin()
int iMax = pow(2.0,i)-1; // maximum value of a valid argument of bin()
while(true) {
std::cout << "Decimal: ";
std::cin >> i;
if (i<0 or i>iMax) {
std::cout << "\nB Integer out of range, 12:1";
return 0;
}
std::cout << "Binary: " << bin(i) << "\n\n";
}
return 0;
}
size_t bin(int i) {return i<2?i:10*bin(i/2)+i%2;}
int digits(size_t i) {return i<10?1:digits(i/10)+1;}
SOLUTION 2
Short. Recursive. Some headers required.
std::string bin(size_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}
This function can return the binary representation of the largest integers as a string. I used the following program to test it:
#include <string> // std::string
#include <iostream> // std::cout, std::cin
int main()
{
std::string s, bin(size_t);
size_t i, x;
std::cout << "Enter exit code: "; // Used to exit the program.
std::cin >> x;
while(i!=x) {
std::cout << "\nDecimal: ";
std::cin >> i;
std::cout << "Binary: " << bin(i) << "\n";
}
return 0;
}
std::string bin(size_t i){return !i?"0":i==1?"1":bin(i/2)+(i%2?'1':'0');}