Count number of distinct digits in decimal representation of an integer - c++

I am new to C++ development and I was hoping someone could help me with something I have been trying to do.
Say for example I want a function that will, given an integer input, return the number of distinct digits it contains.
So for example, if I have three integers:
int a = 19876;
int b = 25644;
int c = 4444;
If I pass 'a' into the function, I would expect the number 5 to be returned.
If 'b' was passed into the function, I would expect '4' to be returned,
If 'c' was passed into the function, then 1 would be returned, as they are the number of distinct numbers.
Could someone please illustrate how I could achieve this?

You mean you want to find the number of different decimal digit in the integer?
int distinct_digits(int value) {
std::ostringstream out;
out << value;
std::string digits = out.str();
std::sort(digits.begin(), digits.end());
return std::unique(digits.begin(), digits.end()) - digits.begin();
}
(not compiled or tested but the basic idea should work)

Using the mod operator and you can count it:
int distinct(int a)
{
int ele[10]={0};
if(a==0) return 1;
if(a<0) a=a*-1;
while(a)
{
int t=a%10;
ele[t]=1;
a=a/10;
}
for (i=0;i<10;i++)
if (ele[i])
count++;
return count;
}
This will work only for both positive numbers and negative numbers.

This could be more concise, but I'm helping you see the way the solution works.
int digitCount(int number) {
// make an array to store whether you've seen a given digit
// note that there are 10 elements, one for each digit
// this will be conveniently indexed 0-9
bool digitSeen[10];
// set each seen digit
int count = 0;
while (number != 0) {
// get the rightmost digit with the modulo operator (%)
int digit = number % 10;
if (digitSeen[digit] == false) {
// only count if this is the first time we have seen it
++count;
digitSeen[digit] = true;
}
// pop off the right-most digit by dividing by 10
number /= 10;
}
return count;
}

You can compute the distinct number thing just fine, but there's no way to go from 'a' to the value of the variable a;. You can hardcode it- but that's fairly maintenance-heavy.

if you mean to return a floating point to get a decimal just return it as a float and the compiler should to an implicit type conversion. this is not generally good code but it works. a better way might be to hand the value to a temporary float like
float a_float = a;
return a_float;

Related

Converting from Decimal to BCD

// 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.

how to find out the number of digits of a number in c++?

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 per­formance-critical, and if this applies to integral types only. The logarithm approach also lets you com­pute 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()

How to get one individual digit from a number that has more than one digit in it

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
}

Returning garbage data from a classes private array

I have a class assignment where I have to write a program that will take a number from the user that is no more than 50 digits long. I have a class called Number that has an array called Value[50] used for holding the value of the number. The number length, as well as the use of arrays, is a requirement of the assignment.
The declaration of the Number class is as follows:
class Number
{
private:
int Value[50];
int NumberSize;
public:
Number();
Number(int&, int&);
int GetValue();
Number& operator=(const Number&);
};
and the definition is
Number :: Number(int& NumberValue, int& NewNumberSize)
{
NumberSize = NewNumberSize;
for (int count = NewNumberSize; count > 0; count --)
{
Value[NewNumberSize] = NumberValue % 10;
NumberValue = NumberValue / 10;
cout << Value[NumberSize] << endl;
}
}
int Number :: GetValue()
{
for (int count2 = 0; count2 < NumberSize; count2 ++)
{
cout << Value[count2] << endl;
}
return 0;
}
I've omitted superfluous information such as #include directives. My problem is with the function Number :: GetValue(), which is written in it's current form for testing purposes. When I run the program
int main()
{
Number blah = Number(12345, 5);
}
(again, a suitable simplification of the real thing), I get the following output
5
4
3
2
1
2347696
2342900
2347268
2352860
-1082078616
The numbers 5 to 1 at the start are expected from the cout found at the and of the Number :: Number(int& NumberValue, int& NewNumberSize) constructor, and the latter half is coming from the the cout in Number :: GetValue(), although the values are unexpected. I was expecting the same values as from the first output stream, only in reverse. The explicit values are not reproducible, although the format is (four seven digit positive integers and a ten digit negative integer). Please note, the cout statements in the class functions are only there for testing purposes ;)
Can anyone see where I'm going wrong here?
You're not actually setting your values.
Value[NewNumberSize] = NumberValue % 10
That just sets the same element (the last element) to the new value, and uses that same value to cout the result as it's calculating it. count isn't used inside the loop. Additionally, You probably want to set values Value[NewNumberSize-1] to Value[0], not Value[NewNumberSize] to Value[1]. (The constructor loop will break before count reaches zero)
Passing simple values by reference when not modifying them is not good practice.
Also, GetValue() does not reach element zero, although that isn't contributing to incorrect output yet.
Value[NewNumberSize] = NumberValue % 10;
This should be
Value[count] = NumberValue % 10;
Also, you need to fix the range of count so that the array index starts from 0 to size-1, rather than 1 to size.
Finally, you are changing the value of NumberValue in the constructor, while the variable is passed by the reference. It's not a good practice. Do not your call-by-reference here or do not change the value of NumberValue.

Convert integer to array

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.