This is what I have:
string decimal_to_binary(int n){
string result = "";
while(n > 0){
result = string(1, (char) (n%2 + 48)) + result;
n = n/2;
}
return result; }
This works, but it doesn't work if I put a negative number, any help?
Just
#include <bitset>
Then use bitset and to_string to convert from int to string
std::cout << std::bitset<sizeof(n)*8>(n).to_string();
It works for negative numbers too.
Well I would recommend calling a separate function for negative numbers. Given that, for example, -1 and 255 will both return 11111111. Converting from the positive to the negative would be easiest instead of changing the logic entirely to handle both.
Going from the positive binary to the negative is just running XOR and adding 1.
You can modify your code like this for a quick fix.
string decimal_to_binary(int n){
if (n<0){ // check if negative and alter the number
n = 256 + n;
}
string result = "";
while(n > 0){
result = string(1, (char) (n%2 + 48)) + result;
n = n/2;
}
return result;
}
This works, but it doesn't work if I put a negative number, any help?
Check whether the number is negative. If so, call the function again with -n and return the concatenated result.
You also need to add a clause to check against 0 unless you want to return an empty string when the input is 0.
std::string decimal_to_binary(int n){
if ( n < 0 )
{
return std::string("-") + decimal_to_binary(-n);
}
if ( n == 0 )
{
return std::string("0");
}
std::string result = "";
while(n > 0){
result = std::string(1, (char) (n%2 + 48)) + result;
n = n/2;
}
return result;
}
Related
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
Below statement gives smallest number whose sum of digit is equal to the given number n.
If the input is 10 output will be 19 (1+9=10)
digits=(c % 9 + 1) * pow(10, (c / 9)) - 1
But when the input is greater like 100000, the output shows Inf. Can anyone help me to solve this, I even tried with unsigned long long int.
Assuming you just want to print the answer and not keep it stored in an integer variable, you can avoid overflow by taking the first digit as c%9and append c/9 number of '9' chars to complete the summation.
std::string getDigits(long long c)
{
if (c == 0)
{
return "0";
}
if (c < 0)
{
return "";
}
auto first = (c % 9);
c -= first;
auto nineCount = c / 9;
std::string result;
if (first != 0)
{
result += std::string(1, (char)(first+'0'));
}
result += std::string(nineCount, '9');
return result;
}
Example run:
int main()
{
std::cout << getDigits(987) << std::endl;
return 0;
}
prints:
69999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999
I am solving a leetcode problem, which the output need to be a binary number without abundant digits.
I have the decimal number and I was trying to use bitset to do the conversion.
I wrote a function to return the number of digit given the number n:
int digitNum (int n){
int digit = 0;
while(n!=0){
n/=2;
digit++;
}
return digit;
}
But when I called it,
int digit = digitNum(res);
result = bitset<digit>(res).to_string();
the digit needs to be a constant. I read the boost::bitset, and I don't see how I can use a dynamic bitset to fix my problem.
http://www.boost.org/doc/libs/1_63_0/libs/dynamic_bitset/dynamic_bitset.html
because it's defining each bit by hand. It doesn't convert to binary anymore.
bitset is a template. Any option in <> is generated at compile-time, so they can't take an input from a variable at runtime to choose template parameters. you can use a loop much like your existing one to do the same job as bitset:
string numToBits(int number)
{
if (number == 0)
return "0";
string temp;
int n = (number > 0) ? number : - number;
while (n > 0)
{
temp = string((n & 1) ? "1" : "0") + temp;
n = n / 2;
}
if(number < 0)
temp = "-" + temp;
return temp;
}
So I've been working on a project for my C++ class, and we have to create a binary calculator. Yet the Professor says the functions should return an 8 bit binary set back. My issue is this
11111111 + 11111111 = 0111111110
Yet in the function we originally create this is the outcome
11111111 + 1111111 = 00000000
Which to me is incorrect. So I changed my function to this
Decimal to Binary
string DecToBin(int num)
{
/*
Purpose: Changing a Decimal to a Binary Set
Pre: Valid positive integer
Post: Returns the valid binary string
*/
string bin = "";
while (num >= 0)
{
bin += (num % 2 == 0 ? "0" : "1");
if (num != 0)
num /= 2;
else break;
}
return bin;
}
Though here lies the issue again
01010101 + 10101010 = 011111111
But my function above returns
01010101 + 10101010 = 111111110
What would be the best possible function to create if one I NEED to return an 8 bit set or if like my said function above which returns the correct answer for some and wrong for the others which I need to figure out why that is in the first place.
Binary to Decimal
int BinToDec(string bin)
{
/*
Purpose: To generate a decimal integer from a string binary set
Pre: Valid String binary set
Post: Output the output decimal integer
*/
int output = 0; //initialize output as 0
int base2Start = 128;//base2 start at 128
int len = bin.length();//get the string length
for (int i = 0; i < len; i++)//iterate
{
if (bin[i] == '1')//if bin[i] in the array of string is a char 1
{
output = output + base2Start;//output gets + base2Start
}//end if condition
base2Start = base2Start / 2;//divide base2Start after each iteration
}//end for loop
return output;//return the output
}
Addition Function
int Addition(string st1, string st2)
{
/*
Purpose: Get's two valid Binary sets, then adds their decimal conversion, and returns the addition
Pre: Need two strings that SHOULD be valid binary
Post: Returns binary from decimal conversion
*/
int first, second;
if (ValidBin(st1))
{
first = BinToDec(st1);
}
else return 0;
if (ValidBin(st2)){
second = BinToDec(st2);
}
else return 0;
add++;
return first + second;
}
bin += (num % 2 == 0 ? "0" : "1");
Should be
bin = (num % 2 == 0 ? "0" : "1") + bin;
Since you each time you are adding the least significant bit of the num to string. So at the end, according to your code, you will have the least significant most left instead of most right.
Edit: In order to truncate the result to 8 bit width change the following line:
return first + second;
By the this one:
return (first + second) & 0xFF; // Same as (first + second) % 256
#include <iostream>
using namespace std;
string sumBinary (string s1, string s2);
int main()
{
cout << "output = "<< sumBinary ("10","10");
}
string sumBinary (string s1, string s2)
{
if (s1.empty())
return s2;
if (s2.empty())
return s1;
int len1 = s1.length() -1;
int len2 = s2.length() -1;
string s3;
s3 = len1 > len2 ? s1: s2;
int len3 = s3.length() -1;
bool carry = false;
while (len1>=0 || len2>=0) {
int i1 = len1>=0? s1[len1--] - '0': 0;
int i2 = len2>=0? s2[len2--] - '0': 0;
// Check if any invalid character
if (i1 <0 || i1>1 || i2<0 || i2>1)
return "";
// 3 bit sum
int sum = i1 ^ i2 ^ carry;
// 3 bit carry
carry = (i1 & carry) | (i2 & carry) | (i1 & i2);
s3[len3--] = '0' + sum;
}
if (carry)
s3 = "1" + s3;
return s3;
}
I am trying to solve this problem.
I am implementing it with strings. Here is my code snippet
string s,ss;
// s and ss both contains integer input.
while(s <= ss )
//while( s<=ss && s.size() <= ss.size())
{
int i = inc, j = dec; // inc and dec are middle values. both equal if odd else different
while((s[j]-'0')==9 && i < len && j>=0){
// for cases like 999
s[i] = s[j] = '0';
i++;
j--;
}
if(j<0){
s = "1" + s;
int l = s[len-1] - '0';
l++;
//cout<<l<<"\n";
s[len] = (l + '0');
}
else{
int l = s[j] - '0';
l++;
s[i] = s[j] = (l+'0');
}
if(s <= ss)
cout<<"out in wild "<<s<<" and "<<ss<<"\n";
}
cout<<s<<endl;
The problem that I am facing is when input is like 999 or 9999. The outer while loop keeps on looping even when the value of s increases, but if I add while( s<=ss && s.size() <= ss.size()) it works completely fine. Why is while(s<=ss) is not working? I rarely use the string class, so I don't understand it completely. Why don't string s= 101 and ss=99 stop the while loop?
Complete code link is here
You are comparing strings with lexicographical order, not numbers , so "101" is less than "99" (because '1' < '9') , e.g.
int main(){
std::string s = "99";
std::string ss = "101";
std::cout << std::boolalpha << (s <= ss);
}
Outputs false.
Notes:
A better design for your program would be to manipulate numbers (int or double ...) and not strings in the first place, so this kind of expressions would naturally work as you expect.
E.g. "101" + "99" is "10199", not "200" ...
But if you really need strings, consider this post to sort strings containing numbers.
As pointed by #Deduplicator, a program that needlessly overuses strings is sometimes called Stringly Typed
Also see std::lexicographical_compare
Since your input explicitly only involves positive integers without leading 0, writing a comparison function is trivial, something like : (untested)
/* Returns 1 if the integer represented by s1 > the integer represented by s2
* Returns -1 if the integer represented by s1 < the integer represented by s2
* Return 0 is both are equals
*
* s1 and s2 must be strings representing positive integers without trailing 0
*/
int compare(const std::string& s1, const std::string& s2)
{
if(s1.size() > s2.size())
return 1;
if(s2.size() > s1.size())
return -1;
for(std::size_t i = 0 ; i < s1.size() ; ++i)
{
if(s1[i] - '0' < s2[i] - '0')
return 1;
if(s2[i] - '0' < s1[i] - '0')
return -1;
}
return 0;
}
While s and ss are string variables, they are compared character by character.
In the case that you mentioned being: s = "101" & ss = "99", by first hand it will check the first character in each string, and as '1' < '9' it exit up with s < ss. I would advise you to convert those values to integers before comparison.
As the s is compared with ss in lexicographical order, I would suggest you to compare one char from tail with one char from head (one by one till you reach the middle) to solve that problem.