// C++ program to convert a decimal
// number to binary number
#include <iostream>
using namespace std;
// 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];
}
// Driver program to test above function
int main()
{
int n = 17;
decToBinary(n);
return 0;
}
So this is a program to convert Decimal numbers to Binary. Now I'm trying to convert Decimal Numbers to BCD. I get the concept, if I have a number like 215 for example, I separate each number [2,1,5] and then convert each number into binary so it would be 0010,0001,0101. I am just confused about implementing it.
First of all, your algorithm simply displays the binary representation of some number n, instead of dividing it into single digits and returning some set of their binary representation.
To make out lives easier, we will be using standard containers and standard algorithms:
[...] if i have a number like 215 for example, i seperate each number [2,1,5] and then covert each number into binary so it would be 0010,0001,0101
Great, it means that we need some sort of a container to hold those three representations, don't we? My choice would be std::vector, since it is incredibly simple and efficient! You can read more about it here.
The mentioned vector will eventually store the binary representations, but here we encounter another problem - we actually need to somehow represent them!
Fortunately enough, the standard gives us a great tool - std::bitset, which is explained here. It is primarily used to make binary operations easier, but one of its great features is that it's also extremely good at simply being a binary representation.
The final function could look like this:
auto dec_to_bin(int n)
{
std::vector<std::bitset<4>> repr;
while(n > 0){
repr.push_back(std::bitset<4>(n % 10));
n /= 10;
}
std::reverse(repr.begin(), repr.end());
return repr;
}
What is happening here?
We firstly create a vector of fixed size bitsets (of the size 4, since every decimal digit can be represented as four binary digits), then as long as our n is greater than zero (you already know why - you are using the same logic in your code), we add (using push_back) a new bitset, that will be treated as binary representation of modulo of your number (i.e. the last digit).
Keep in mind though, that by doing this, we created the vector in the reversed order. The last two things we have to do is simply reverse and return it!
Finally, we can use our function in main as such:
int main()
{
for(auto b : dec_to_bin(215)){
std::cout << b << ' ';
}
}
This will print 0010 0001 0101, which was your desired output for the number 215
Can't you just replace the % 2 and / 2 with % 10 and / 10? The variables will be named wrong but that's the algorithmic change.
You simply have to divide your integer by digits and call your function for each digit:
void decToBCD(int n) {
// array to store digits
int digits[10];
// counter for digits
int i = 0;
while (n > 0) {
// storing remainder in digit array
digits[i] = n % 10;
n = n / 10;
i++;
}
// printing binary representation of digits
for (int j = i - 1; j >= 0; j--) {
decToBinary(digits[j]);
cout << " ";
}
}
I would update what you have to return a string from decToBinary rather than printing to cout, you can then write decToBCD which uses modulo 10 to work out the integer for each digit of the number (in the same way you used modulo 2 and divide by 2 to get each bit in decToBinary), and call decToBinary for each integer digit and concatenates the strings of binary digits to give the full result.
Related
I have a rand number generator.
Now my question is how do I get for instance the first/second/third/fourth digit of the generated random number.
Implementing this so the user can use a hint when guessing the number.
example: result(rand): 9876
print hint 1: second number 8
print hint 2: fourth number 6
Whats the best way to tackle this? I've been thinking to convert the string to an char array in order to print out the certain locations where the values are being kept but that won't work I guess.
Correct me if my way of asking this questions is very bold.
int nummer = 4;
std :: string result = "";
for (int i = 0; i < nummer; i++)
{
result.push_back(rand()%10 + '0');
}
You have two options for solving this problem:
Create one random number between 0 and 9999 and then calculate the individual digits.
Create four random numbers between 0 and 9 which represent the individual digits and then, if necessary, calculate the whole number from the individual digits.
Normally, doing option #1 would be more straightforward. You seem to be going for option #2. Both ways are possible and which one is better probably depends on whether your program works more with the number as a whole or with individual digits.
If you decide to do option #2, then the question arises whether you want to work with ASCII character codes between '0' and '9' (i.e. codes between 48 and 57) or with actual numbers between 0 and 9. Normally, it is a bit easier to work with the actual numbers instead of ASCII character codes, but both ways are feasible.
Personally, I would solve it the following way:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
//seed random number generator
std::srand( std::time(nullptr) );
//note that NUM_DIGITS should not be set so high
//that MAX_NUMBER is not representable as an `int`
constexpr int NUM_DIGITS = 4;
//set this to the highest possible number that
//corresponds to NUM_DIGITS
constexpr int MAX_NUMBER = 9999;
//this variable holds the entire number
int random;
//this array holds the individual digits
int digits[NUM_DIGITS];
///generate the random number
random = std::rand()%(MAX_NUMBER+1);
//calculate the individual digits of the random number
int remaining = random;
int divisor = (MAX_NUMBER+1) / 10;
for ( int i = 0; i < NUM_DIGITS; i++ )
{
digits[i] = remaining / divisor;
remaining = remaining % divisor;
divisor/= 10;
}
//print the whole random number
std::cout << "Whole random number:\n" << random << "\n\n";
//print the individual digits
std::cout << "Individual digits:\n";
for ( int i = 0; i < NUM_DIGITS; i++ )
{
std::cout << digits[i] << "\n";
}
}
Sample output (actual output depends on random number seed):
Whole random number:
8695
Individual digits:
8
6
9
5
I've been thinking to convert the string to an char array but that won't work I guess.
I see no reason to do this. In your posted code, you can simply write
result[0]
result[1]
result[2]
result[3]
to access the individual digits of the number.
In that respect, converting a std::string to a C-style character array has no advantages.
The code you've written is fine.
Whether you store the characters in an array or a string, you can access the elements using result[i] where i starts at 0.
I've been thinking to convert the string to an char array but that won't work I guess.
Using std::string is usually a better idea - still possible but a little harder to screw them up, and they're more powerful generally, but you could use a char array if you wanted:
char result[] = "0000"; // will have null terminator
for (int i = 0; i < 4; ++i)
result[i] = rand() % 10 + '0';
Letting result be a 5-character array - with a null terminator - means you can still print all four digits easily with std::cout << result.
Alternatively, you could pick a random 4-digit number and convert it to a string of a particular width, using '0's to pad:
#include <iostream>
#include <iomanip>
int main() {
std::ostringstream oss;
oss << std::setw(4) << std::setfill('0') << rand() % 10000;
std::cout << '[' << oss.str() << "]\n";
}
I know the common way to count the digits of an int is using a loop, and keep dividing by 10 until it's gone. I'm curious that can I first convert the int into a string and then count the length of the string to get the number of digits (assume there are only positive ints)?
If this method is possible, then what is the difference between using a loop?
Yes, you can. NO, you don't want to actually do it. It will be 2 orders of magnitude (~100x) slower than using the loop. Why? Because integer to string conversion not only has to execute some sort of a loop to generate the string's digits, but also has to allocate and deallocate the heap to hold the string, unless the string has some sort of a small-string optimization.
In most cases, people would consider your approach to be an ugly hack. If you want to count digits in an integer, you don't even need a loop:
constexpr int digits(int32_t x) {
return
(x < 0 ? digits(-x) :
(x < 10 ? 1 :
(x < 100 ? 2 :
(x < 1000 ? 3 :
(x < 10000 ? 4 :
(x < 100000 ? 5 :
(x < 1000000 ? 6 :
(x < 10000000 ? 7 :
(x < 100000000 ? 8 :
(x < 1000000000 ? 9 :
10))))))))));
}
Yes, this method is possible.
The difference is that there is an extra step involved if you convert to string first. The string conversion actually does something similar to the loop you described.
Here is an example how to count integer digits via string length:
#include <string>
int number_of_digits(int number) {
// Using C++11
return std::to_string(number).length();
}
You could use the itoa() function (in this example below, _itoa_s() is a safe version of itoa()). This function basically transforms an integer to a string (itoa=integer to alphabet).
Here's an example:
int number;
char temp[12];
cout << "Enter your number: ";
cin >> number;
//itoa(number, temp, 10);
//_itoa_s(number, temp, 12, 10);
_itoa_s(number, temp, 10);
cout << "The number of digits is: " << strlen(temp) << endl;
itoa() takes 3 parameters: the number you're going to convert (number), the buffer where the number will be held after the conversion (temp), and the numeral system to which you're converting to (10 is for base-10, aka decimal numeral system).
_itoa_s() takes a 4th parameter, the size of the buffer. There is also a templated version of _itoa_s() specifically for static arrays (which is used in the example above). It takes 3 parameters, letting the compiler deduce the buffer size for the 4th parameter.
Also, I chose 12 characters for the temp buffer because the max value of a integer is 2,147,483,647, which has 10 digits, plus room for a null terminator and some extra alignment.
The obvious divide-by-10 method will return 0 for an input of 0, which may or may not be what you want. Other than that, both methods will return the same, but divide-by-10 is much faster.
If you use std::string as I do in the example below (which allocates memory), then the divide-by-10 method is easily hundreds of times faster.
int numlen_using_divide_by_10(int n) {
int ret = 0;
for (; n; n /= 10) ++ret;
return ret;
}
int numlen_using_string(int n) {
return std::to_string(n).size();
}
I wanna find out the number of digits of a number in c++ but I don't know what can I do? for example number of digits 7676575.
Take the ceiling of the base-10 logarithm of the number. (Or more generally "base-N" for the number of digits in base N.)
In code: std::ceil(std::log10(n + 1)), and make sure to #include <cmath>.
(You'll get the answer 0 for input 0 as a special case. It's up to you what to do about negative numbers.)
The code in #Knaģis's answer is possibly more efficient, since divisions by the constant 10 can be turned into multiplications by the compiler and are fairly cheap. You have to profile and compare if this is performance-critical, and if this applies to integral types only. The logarithm approach also lets you compute the number of digits in a hypothetical decimal expansion of very large floating point numbers.
int i = 7676575;
int digits = i == 0 ? 1 : 0;
i = abs(i); // handle negative numbers as well
while (i > 0)
{
digits++;
i /= 10;
}
// -or- if you prefer do/while then a shorter sample (by Kerrek SB)
int i = 7676575;
int digits = 0;
i = abs(i); // handle negative numbers as well
do { digits++; } while (i /= 10);
Just put it in a string and get its length;
int number = getNumberFromSomewhere();
stringstream ss;
ss << number;
size_t numDigits = ss.str().length();
template <typename T>
int getdigits(T v)
{
T i = std::abs(v);
if (i < 10) return 1;
else if (i < 100) return 2;
...
else if (i < 100000000) return 8;
else if (i < 1000000000) return 9;
}
And so on, you can extend to include long range, not only int. I'm not sure if this is faster than divide, but why not - it's just 10 comparisons.
I suppose templates black magic can be used to generate functions with only needed number of ifs, but who really cares. But you can ensure T is integer using std::enable_if<std::is_integer<T>::value>.
You can convert to string and check the length of the string:
std::to_string(number).size()
So I have a four digit number that is player-input in a simple puzzle I am making, I want to be able to check each digit, say I want to check the second digit to the right, if the number happens to be 4601 then of course it will be 6 but is their a faster way other than testing every single four digit number?
I found a few results with search but they didn't help, they just confused me more, please phrase any answers so anyone can understand them.
Also i am using c++.
To retrieve the second most significant (base ten) digit from an arbitrary integer i you could do:
while (i >= 100)
i /= 10;
return i % 10;
Of course, this assumes the number greater than or equal to 10 to begin with. If you need to preserve the number, then you will (obviously) want to be operating on a copy.
EDIT:
One could define a function for extracting an arbitrary digit using either arithmetic or string operations.
Arithmetic solution:
int extractDigit(size_t digit, int n) {
int mask = 1;
while ( digit --> 0 )
mask *= 10;
if (n < mask / 10) { // insufficient digits
return -1; // or some other appropriate error handling.
while ( n >= mask )
n /= mask;
return n % 10;
}
String solution:
#include <sstream>
#include <string>
using std::string;
using std::stringstream;
int extractDigit(size_t digit, int n) {
string result = static_cast<stringstream&>(stringstream() << n).str();
if (result.size() < digit) {
return -1;
}
return result[digit-1] - '0';
}
Both of these solutions implicitly assume that n will be non-negative. You could enforce this pre-condition by using an unsigned data type if you need to. Also, both of these functions are defining the digit positions such that the most significant is in position 1, and the positions increase to the right.
I am not guessing anything about what you going to do after you have the digit.But if its only the digit you want to have then you could use below:
int a=1234;
char b[4];
sprintf(b,"%d",a);
char c=b[1];
Now c has the second digit of your 4 digit number.
like wise you can access all the digits using the index to character array b
for a c++ equivalent pls see below:
std::ostringstream out;
out << age;
Now out.str()[1] will show the second digit.
You can read the number as an int and convert it to a char array and check each char as a digit
Example:
char digits[5];
int number;
//Read number in
scanf("%d",&number);
//Make sure it's 4 digits
number%=10000;
//Convert it to a char array
sprintf(digits,"%d",number)
if(digits[1]=='6')
{
//do stuff
}
I would like to convert an integer into an array, so that it looks like the following:
int number = 123456 ;
int array[7] ;
with the result:
array[0] = 1
array[1] = 2
...
array[6] = 6
Perhaps a better solution is to work backwards:
123456 % 10 = 6
123456 / 10 = 12345
12345 % 10 = 5
12345 / 10 = 1234
just use modular arithmetic:
int array[6];
int number = 123456;
for (int i = 5; i >= 0; i--) {
array[i] = number % 10;
number /= 10;
}
You can extract the last digit of the number this way:
int digit = number % 10;
number /= 10;
Note that you should also check whether number is positive. Other values require additional handling.
Here what I came up with, the integerToArray function returns a vector that is converted from the integer value. you can test it with the main function as well:
#include <iostream>
#include <vector>
using namespace std;
vector <int> integerToArray(int x)
{
vector <int> resultArray;
while (true)
{
resultArray.insert(resultArray.begin(), x%10);
x /= 10;
if(x == 0)
return resultArray;
}
}
int main()
{
vector <int> temp = integerToArray(1234567);
for (auto const &element : temp)
cout << element << " " ;
return 0;
}
//outputs 1 2 3 4 5 6 7
Take the log10 of the number to get the number of digits. Put that in, say pos, then, in a loop, take the modulo of 10 (n % 10), put the result in the array at position pos. Decrement pos and divide the number by 10. Repeat until pos == 0
What did you want to do with the sign if it's negative?
#include <cmath>
#include <vector>
std::vector<int> vec;
for (int i = log10(input); i >= 0; i--)
{
vec.push_back(input / int(std::pow(10, i)) % 10);
}
Might be a good approach, I think
The easiest way I can imagine now is:
char array[40];
int number = 123456;
memset(array, 0x00, sizeof(array));
sprintf(array, "%d", number);
Additionally you can convert each digit to int just subtracting the char value by 0x30.
EDIT: If this is a homework, your teacher you probably ask you to write the program using % operator though (example 12 % 10 = 2). If this is the case, good homework ;-)
You can use modulus to determine the last digit.
And you can use division to move another digit to the last digit's place.
You can't simply "convert" it. The integer is not represented in software in decimal notation. So the individual digits you want don't exist. They have to be computed.
So, given an arbitrary number, how can you determine the number of ones?
We could divide by ten, and then take the remainder: For 123, the division would give 12, and then there's a remainder of 3. So we have 3 ones. The 12 tells us what we have past the ones, so it can be our input for the next iteration. We take that, divide by 10, and get 1, and a remainder of 2. So we have 2 in the tens place, and 1 left to work with for the hundreds. Divide that by 10, which gives us zero, and a remainder of 1. So we get 1 in the hundreds place, 2 in the tens place, and 3 in the ones place. And we're done, as the last division returned zero.
See SO question Language showdown: Convert string of digits to array of integers? for a C/C++ version (as well as other languages).
if this is really homework then show it your teacher - just for fun ;-)
CAUTION! very poor performance, clumsy way to reach the effect you expect and generally don't do this at home(work) ;-)
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
typedef std::vector< int > ints_t;
struct digit2int
{
int operator()( const char chr ) const
{
const int result = chr - '0';
return result;
}
};
void foo( const int number, ints_t* result )
{
std::ostringstream os;
os << number;
const std::string& numberStr = os.str();
std::transform(
numberStr.begin(),
numberStr.end(),
std::back_inserter( *result ),
digit2int() );
}
int main()
{
ints_t array;
foo( 123456, &array );
std::copy(
array.begin(),
array.end(),
std::ostream_iterator< int >( std::cout, "\n" ) );
}
If you wanted to turn it into a string then it would be really easy, just do what everyone else is saying about using the % operator:
Let's say num = 123, we can do this:
string str;
while (num > 0)
{
str = (num % 10) + str; //put last digit and put it into the beginning of the string
num = num /10; //strip out the last digit
}
Now you can use str as an array of chars. Doing this with an array is a hassle because putting things in the beginning of an array requires you to shift everything else. What we can do is, instead of putting each digit into a string, we can put it into a stack. It will put it in a backwards order like this: 3 2 1. Then we can pop off the top number one by one and put that into an array in the correct order. You array will look like this: 1 2 3. I will leave the implementation to you since this is homework.
#Broam has a good solution, but like he stated, it's for working backwards. I think the OP or whoever comes looking into this thread will want it forwards and that's why I'm posting this. If you have a better solution, please reply, I'm interested as well.
To convert an integer to array, you can do the steps below:
Get the total number of digits in a number to which we want to convert to
array.For this purpose, we will use count_digits() function which will return total no of digits after ignoring leading zeros.
digits = count_digits(n);
Now we will dynamically allocate memory for our resulting array, just like
int* arr = new int[count_digits(n)]
After allocating memory, we will populate the array using the for loop below
int digits = count_digits(num);
for (int i = digits; i > 0; i--){
arr[i-1] = num % 10;
num = num / 10;
}
After performing the steps above, we will be able to convert an integer to array. Remember, num is the number that we want to convert into array and digits is the variable which gives us the number of digits in a given number ignoring leading zeros.