Identify the digits in a given number. - c++

I'm new to programming, and I'm stuck at a problem. I want my program to identify the separate digits in a given number, like if I input 4692, it should identify the digits and print 4 6 9 2. And yeah, without using arrays.

A perfect recursion problem to tackle if you're new to programming...
4692/1000 = 4
4692%1000 = 692
692/100 = 6
692%100 = 92
92/10 = 9
92%10 = 2
You should get the idea for the loop you should use now, so that it works for any number. :)

Haven't written C code in year, but this should work.
int i = 12345;
while( i > 0 ){
int nextVal = i % 10;
printf( "%d", nextVal );
i = i / 10;
}

Simple and nice
void PrintDigits(const long n)
{
int m = -1;
int i = 1;
while(true)
{
m = (n%(10*i))/i;
i*= 10;
cout << m << endl;
if (0 == n/i)
break;
}
}

Another approach is to have two loops.
1) First loop: Reverse the number.
int j = 0;
while( i ) {
j *= 10;
j += i % 10;
i /= 10;
}
2) Second loop: Print the numbers from right to left.
while( j ) {
std::cout << j % 10 << ' ';
j /= 10;
}
This is assuming you want the digits printed from right to left. I noticed there are several solutions here that do not have this assumption. If not, then just the second loop would suffice.

I think the idea is to have non reapeating digits printed (otherwise it would be too simple)... well, you can keep track of the already printed integers without having an array encoding them in another integer.
some pseudo C, to give you a clue:
int encoding = 0;
int d;
while (keep_looking()) {
d = get_digit();
if (encoding/(2**d)%2 == 0) {
print(d);
encoding += 2**d;
}
}

Here is a simple solution if you want to just print the digits from the number.
#include <stdio.h>
/**
printdigits
*/
void printDigits(int num) {
char buff[128] = "";
sprintf(buff, "%d ", num);
int i = 0;
while (buff[i] != '\0') {
printf("%c ", buff[i]);
i++;
}
printf("\n");
}
/*
main function
*/
int main(int argc, char** argv) {
int digits = 4321;
printDigits(digits);
return 0;
}

Is it correct
int main()
{
int number;
cin>>number;
int nod=0;
int same=number;
while(same){
same/=10;
nod++;
}
while(nod--){
cout<<(int)number/(int)pow10(nod)%10<<"\t";
}
return 0;
}

Related

Code to convert decimal to hexadecimal without using arrays

I have this code here and I'm trying to do decimal to hexadecimal conversion without using arrays. It is working pretty much but it gives me wrong answers for values greater than 1000. What am I doing wrong? are there any counter solutions? kindly can anyone give suggestions how to improve this code.
for(int i = num; i > 0; i = i/16)
{
temp = i % 16;
(temp < 10) ? temp = temp + 48 : temp = temp + 55;
num = num * 100 + temp;
}
cout<<"Hexadecimal = ";
for(int j = num; j > 0; j = j/100)
{
ch = j % 100;
cout << ch;
}
There's a couple of errors in the code. But elements of the approach are clear.
This line sort of works:
(temp < 10) ? temp = temp + 48 : temp = temp + 55;
But is confusing because it's using 48 and 55 as magic numbers!
It also may lead to overflow.
It's repacking hex digits as decimal character values.
It's also unconventional to use ?: in that way.
Half the trick of radix output is that each digit is n%r followed by n/r but the digits come out 'backwards' for conventional left-right output.
This code reverses the hex digits into another variable then reads them out.
So it avoids any overflow risks.
It works with an unsigned value for clarity and a lack of any specification as how to handle negative values.
#include <iostream>
void hex(unsigned num){
unsigned val=num;
const unsigned radix=16;
unsigned temp=0;
while(val!=0){
temp=temp*radix+val%radix;
val/=radix;
}
do{
unsigned digit=temp%16;
char c=digit<10?'0'+digit:'A'+(digit-10);
std::cout << c;
temp/=16;
}while(temp!=0);
std::cout << '\n';
}
int main(void) {
hex(0x23U);
hex(0x0U);
hex(0x7U);
hex(0xABCDU);
return 0;
}
Expected Output:
23
0
8
ABCD
Arguably it's more obvious what is going on if the middle lines of the first loop are:
while(val!=0){
temp=(temp<<4)+(val&0b1111);
val=val>>4;
}
That exposes that we're building temp as blocks of 4 bits of val in reverse order.
So the value 0x89AB with be 0xBA98 and is then output in reverse.
I've not done that because bitwise operations may not be familiar.
It's a double reverse!
The mapping into characters is done at output to avoid overflow issues.
Using character literals like 0 instead of integer literals like 44 is more readable and makes the intention clearer.
So here's a single loop version of the solution to the problem which should work for any sized integer:-
#include <iostream>
#include <string>
using namespace std;
void main(int argc, char *argv[1])
{
try
{
unsigned
value = argc == 2 ? stoi(argv[1]) : 64;
for (unsigned i = numeric_limits<unsigned>::digits; i > 0; i -= 4)
{
unsigned
digit = (value >> (i - 4)) & 0xf;
cout << (char)((digit < 10) ? digit + 48 : digit + 55);
}
cout << endl;
}
catch (exception e)
{
cout << e.what() << endl;
}
}
There is a mistake in your code, in the second loop you should exit when j > original num, or set the cumulative sum with non-zero value, I also changed the cumulative num to be long int, rest should be fine.
void tohex(int value){
long int num = 1;
char ch = 0;
int temp = 0;
for(int i = value; i > 0; i = i/16)
{
temp = i % 16;
(temp < 10) ? temp = temp + 48 : temp = temp + 55;
num = num * 100 + temp;
}
cout<<"Hexadecimal = ";
for(long int j = num; j > 99; j = j/100)
{
ch = j % 100;
cout << ch;
}
cout << endl;
}
If this is a homework assignment, it is probably related to the chapter on Recursivity. See a solution below. To understand it, you need to know
what a lookup table is
what recursion is
how to convert a number from one base to another iteratively
basic io
void hex_out(unsigned n)
{
static const char* t = "0123456789abcdef"; // lookup table
if (!n) // recursion break condition
return;
hex_out(n / 16);
std::cout << t[n % 16];
}
Note that there is no output for zero. This can be solved simply by calling the recursive function from a second function.
You can also add a second parameter, base, so that you can call the function this way:
b_out(123, 10); // decimal
b_out(123, 2); // binary
b_out(123, 8); // octal

Duplicates in X element array

I have an interval (m,n) and there I have to print out all the numbers which have different digits. I wrote this, but it only works for 2 digit numbers. I simply do not know how to make it work for anything but 2 digit numbers. I imagine that, if I added as much for loops as the digits of my number it would work, but the interval(m,n) isn't specified so it has to be something reliable. I've been trying to solve this problem on my own for 6 damn hours and I'm absolutely fed up.
Input 97,113;
Output 97,98,102,103,104,105,106,107,108,109
Numbers 99,100,101,110+ don't get printed, because they have 2 digits that are
the same.
#include<conio.h>
#include<math.h>
#include<stdio.h>
int main()
{
int m,n,test,checker=0;
scanf("%d%d",&m,&n);
if(m>n)
{
int holder=n;
n=m;
m=holder;
}
for(int start=m;start<=n;start++)
{
int itemCount=floor(log10(abs(start)))+1;
int nums[itemCount];
int index=0;
test=start;
do
{
int nextVal = test % 10;
nums[index++]=nextVal;
test = test / 10;
}while(test>0);
for (int i = 0; i < itemCount - 1; i++)
{ // read comment by #nbro
for (int j = i + 1; j < itemCount; j++)
{
if (nums[i] == nums[j])
{
checker++;
}
}
if(checker==0)printf("%d ",start);
}
checker=0;
}
}
Since you tagged this as C++, here is a very simple solution using simple modulus and division in a loop. No conversion to string is done.
#include <iostream>
#include <bitset>
bool is_unique_digits(int num)
{
std::bitset<10> numset = 0;
while (num > 0)
{
// get last digit
int val = num % 10;
// if bit is on, then this digit is unique
if (numset[val])
return false;
// turn bit on and remove last digit from number
numset.set(val);
num /= 10;
}
return true;
}
int main()
{
for (int i = 97; i <= 113; ++i)
{
if (is_unique_digits(i))
std::cout << i << "\n";
}
}
The is_unique_digit function simply takes the number and repeatedly extracts the digits from it by taking the last digit in the number. Then this digit is tested to see if the same digit appears in the bitset. If the number already exists, false is immediately returned.
If the number is not in the bitset, then the bit that corresponds to that digit is turned "on" and the number is divided by 10 (effectively removing the last digit from the number). If the loop completes, then true is returned.
Live Example
As an idea for a design:
print the number to a string, if it isn't a string already;
declare an array of int d[10]; and set it to all zeroes
for each ascii digit c of the string,
if (d[c-'0']==1) return 0; // this digit exists already in the number
else d[c-'0']= 1;
just put if(checker==0)printf("%d ",start); outside of second loop the loop
like this
for (int i = 0; i < itemCount - 1; i++)
{
for (int j = i + 1; j < itemCount; j++)
{
if (nums[i] == nums[j])
{
checker++;
break;
}
}
}
if(checker==0)
printf("%d ",start);
checker=0;
However instead of using two nested for loop you can use count array which is more efficient
to check 1 number, you can do
X=10; //number to analyze
char counts[10]; for int i=0;i<10;i++) counts[i]=0;
char number[10];
sprintf(&number,"%s",X); bool bad=false;
for(int i=0;i<strlen(number);i++)
{
if(++counts[number[i]-'0']>1) {bad=true;break;}
}`

converting a string (containing numbers) into an integer and returning that integer

i'm working on a code right now in C++, in which i'm supposed to make a function which receives a string of numbers and converts it into an integer then returns that value. for example if i pass "4569" as string, it will return 4569 integer value.
can anyone help me point out where i'm wrong ??? thanks in advance :)
#include<iostream>
#include<cstdlib>
using namespace std;
void getInput(char arr[] , int size )
{
cout<<"ENTER THE ARRAY"<<endl;
cin.getline(arr,size);
}
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for( int i=y ; i>=0 ; i--)
{
int n= source[i];
sum = (sum + (n * multiply));
multiply = (multiply *10);
}
return sum;
}
int main()
{
const int size =100;
char inputArr [size];
getInput (inputArr, size );
int x = stringToInteger (inputArr );
cout<<"THE RETURNED INTEGER VALUE IS"<<endl;
cout<<x<<endl;
return 0;
}
First, you're starting at the character after the end of the string. If the length (returned by strlen) is y, then valid indexes are 0 <= i < y. So your loop wants to start from y-1.
for( int i=y-1 ; i>=0 ; i--)
^^
Then, you need to convert each ASCII digit into a value from 0 to 9, by subtracting the ASCII value for '0':
int n= source[i] - '0';
^^^^^
Then you should probably detect and handle erroneous input, including values that are too large to be represented by int.
Then, once you've learnt how to implement this in C, throw it away and use the C++ library:
std::string input;
std::getline(std::cin, input);
int x = std::stoi(input);
Try,
#include <stdlib.h>
and in your main():
int x = atoi(inputArr);
I'm not sure why you aren't using atoi or std::stoi, but your algorithm has a logical flaw:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
That said, if this was something other than a homework assignment, you should be using the solutions posted https://stackoverflow.com/a/18238566/529761 or https://stackoverflow.com/a/18238682/529761 (depending on your language requirements).
Also, even this change has 1 potential problem: If the source contains non-numeric characters, it will not work properly. A simple way to approach it is to break out if you encounter a character that shouldn't be there:
int stringToInteger(char source[])
{
int sum = 0;
int y=strlen(source);
int multiply = 1;
for(int i=y - 1; i >= 0; i--) // you were starting at y, which is 1 passed the end of the array
{
int n = (int)(source[i] - '0');
if (n < 0 || n > 9)
break;
sum += (n * multiply); // += makes this more readable
multiply *= 10; // same with *=
}
return sum;
}
No need to call a strlen -- until you are allowed to use library functions (the above-mentioned atoi and strtol), you can use this:
int stringToInteger(char *source)
{
int sum = 0;
if (source)
while (*source >= '0' && *source <= '9')
{
sum = 10*sum + *source - '0';
source++;
}
return sum;
}
As implied in about every other answer, you forgot there is a difference between the ASCII character '0' and the binary value 0.

Is this an inefficent way to convert from a binary string to decimal value?

while(i < length)
{
pow = 1;
for(int j = 0; j < 8; j++, pow *=2)
{
ch += (str[j] - 48) * pow;
}
str = str.substr(8);
i+=8;
cout << ch;
ch = 0;
}
This seems to be slowing my program down a lot. Is it because of the string functions I'm using in there, or is this approach wrong in general. I know there's the way where you implement long division, but I wanted to see if that was actually more efficient than this method. I can't think of another way that doesn't use the same general algorithm, so maybe it's just my implementation that is the problem.
Perhaps you want might to look into using the standard library functions. They're probably at least as optimised as anything you run through the compiler:
#include <iostream>
#include <iomanip>
#include <cstdlib>
int main (void) {
const char *str = "10100101";
// Use str.c_str() if it's a real C++ string.
long int li = std::strtol (str, 0, 2);
std::cout
<< "binary string = " << str
<< ", decimal = " << li
<< ", hex = " << std::setbase (16) << li
<< '\n';
return 0;
}
The output is:
binary string = 10100101, decimal = 165, hex = a5
You are doing some things unnecessarily, like creating a new substring for each each loop. You could just use str[i + j] instead.
It is also not necessary to multiply 0 or 1 with the power. Just use an if-statement.
while(i < length)
{
pow = 1;
for(int j = 0; j < 8; j++, pow *=2)
{
if (str[i + j] == '1')
ch += pow;
}
i+=8;
cout << ch;
ch = 0;
}
This will at least run a bit faster.
short answer could be:
long int x = strtol(your_binary_c++_string.c_str(),(char **)NULL,2)
Probably you can use int or long int like below:
Just traverse the binary number step by step, starting from 0 to n-1, where n is the most significant bit(MSB) ,
multiply them with 2 with raising powers and add the sum together. E.g to convert 1000(which is binary equivalent of 8), just do the following
1 0 0 0 ==> going from right to left
0 x 2^0 = 0
0 x 2^1 = 0;
0 x 2^2 = 0;
1 x 2^3 = 8;
now add them together i.e 0+0+0+8 = 8; this the decimal equivalent of 1000. Please read the program below to have a better understanding how the concept
work. Note : The program works only for 16-bit binary numbers(non-floating) or less. Leave a comment if anything is not clear. You are bound to receive a reply.
// Program to convert binary to its decimal equivalent
#include <iostream>
#include <math.h>
int main()
{
int x;
int i=0,sum = 0;
// prompts the user to input a 16-bit binary number
std::cout<<" Enter the binary number (16-bit) : ";
std::cin>>x;
while ( i != 16 ) // runs 16 times
{
sum += (x%10) * pow(2,i);
x = x/10;
i++;
}
std::cout<<"\n The decimal equivalent is : "<<sum;
return 0;
}
How about something like:
int binstring_to_int(const std::string &str)
{
// 16 bits are 16 characters, but -1 since bits are numbered 0 to 15
std::string::size_type bitnum = str.length() - 1;
int value = 0;
for (auto ch : str)
{
value |= (ch == '1') << bitnum--;
}
return value;
}
It's the simplest I can think of. Note that this uses the new C++11 for-each loop construct, if your compiler can't handle it you can use
for (std::string::const_iterator i = str.begin(); i != str.end(); i++)
{
char ch = *i;
// ...
}
Minimize the number of operations and don't compute things more than once. Just multiply and move up:
unsigned int result = 0;
for (char * p = str; *p != 0; ++p)
{
result *= 2;
result += (*p - '0'); // this is either 0 or 1
}
The scheme is readily generalized to any base < 10.

reverse the position of integer digits?

i have to reverse the position of integer like this
input = 12345
output = 54321
i made this but it gives wrong output e.g 5432
#include <iostream>
using namespace std;
int main(){
int num,i=10;
cin>>num;
do{
cout<< (num%i)/ (i/10);
i *=10;
}while(num/i!=0);
return 0;
}
Here is a solution
int num = 12345;
int new_num = 0;
while(num > 0)
{
new_num = new_num*10 + (num % 10);
num = num/10;
}
cout << new_num << endl;
Your loop terminates too early. Change
}while(num/i!=0);
to
}while((num*10)/i!=0);
to get one more iteration, and your code will work.
If you try it once as an example, you'll see your error.
Input: 12
first loop:
out: 12%10 = 2 / 1 = 2
i = 100
test: 12/100 = 0 (as an integer)
aborts one too early.
One solution could be testing
(num % i) != num
Just as one of many solutions.
Well, remember that integer division always rounds down (or is it toward zero?) in C. So what would num / i be if num < 10 and i = 10?
replace your while statement
with
while (i<10*num)
If I were doing it, I'd (probably) start by creating the new value as an int, and then print out that value. I think this should simplify the code a bit. As pseudocode, it'd look something like:
output = 0;
while (input !=0)
output *= 10
output += input % 10
input /= 10
}
print output
The other obvious possibility would be to convert to a string first, then print the string out in reverse:
std::stringstream buffer;
buffer << input;
cout << std::string(buffer.str().rbegin(), buffer.str().rend());
int _tmain(int argc, _TCHAR* argv[])
{
int x = 1234;
int out = 0;
while (x != 0)
{
int Res = x % (10 );
x /= 10;
out *= 10;
out += Res;
}
cout << out;
}
This is a coding assignment for my college course. This assignment comes just after a discussion on Operator Overloading in C++. Although it doesn't make it clear if Overloading should be used for the assignment or not.
The following code works for a two-digit number only.
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
cout << (n%10) << (n/10);
return 0;
}
int a,b,c,d=0;
cout<<"plz enter the number"<<endl;
cin>>a;
b=a;
do
{
c=a%10;
d=(d*10)+c;
a=a/10;
}
while(a!=0);
cout<<"The reverse of the number"<<d<<endl;
if(b==d)
{
cout<<"The entered number is palindom"<<endl;
}
else
{
cout<<"The entered number is not palindom"<<endl;
}
}
template <typename T>
T reverse(T n, size_t nBits = sizeof(T) * 8)
{
T reverse = 0;
auto mask = 1;
for (auto i = 0; i < nBits; ++i)
{
if (n & mask)
{
reverse |= (1 << (nBits - i - 1));
}
mask <<= 1;
}
return reverse;
}
This will reverse bits in any signed or unsigned integer (short, byte, int, long ...). You can provide additional parameter nBits to frame the bits while reversing.
i. e.
7 in 8 bit = 00000111 -> 11100000
7 in 4 bit = 0111 -> 1110
public class TestDS {
public static void main(String[] args) {
System.out.println(recursiveReverse(234));
System.out.println(recursiveReverse(234 ,0));
}
public static int reverse(int number){
int reversedNumber = 0;
int temp = 0;
while(number > 0){
//use modulus operator to strip off the last digit
temp = number%10;
//create the reversed number
reversedNumber = reversedNumber * 10 + temp;
number = number/10;
}
return reversedNumber;
}
private static int reversenumber =0;
public static int recursiveReverse(int number){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number);
}
public static int recursiveReverse(int number , int reversenumber){
if(number <= 0){
return reversenumber;
}
reversenumber = reversenumber*10+(number%10);
number =number/10;
return recursiveReverse(number,reversenumber);
}
}
I have done this simply but this is applicable upto 5 digit numbers but hope it helps
#include<iostream>
using namespace std;
void main()
{
int a,b,c,d,e,f,g,h,i,j;
cin>>a;
b=a%10;
c=a/10;
d=c%10;
e=a/100;
f=e%10;
g=a/1000;
h=g%10;
i=a/10000;
j=i%10;
cout<<b<<d<<f<<h<<j;
}`