i know to reverse the digits of a number(integer) in c but my questions is how can we reverse the digits of a real no
for e.g 1200.23 gets reversed as 32.0021
code for integers
#include <stdio.h>
/* Iterative function to reverse digits of num(integer)*/
int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}
/*Driver program to test reversDigits*/
int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));
getchar();
return 0;
}
Obviously your paramater needs to be floating point type.
You could convert double to string then reverse the string then convert back to double:
#include <string>
#include <sstream>
template<typename T>
std::string toString(T t)
{
std::stringstream ss;
ss << t;
rteurn ss.str();
}
double reversDigits(double num)
{
std::string s = std::to_string(num);
std::reverse(s.begin(), s.end());
double d;
std::stringstream ss(s);
ss >> d;
return d;
}
You could use the following code, where the iostream library is being used:
#include <iostream>
#include <math.h>
using namespace std;
int main() {
double pass = 0;
double n;
double result=0;
cout << "Please enter a number to reverse" << endl;
cin >> n;
while (trunc(n / pow(10.0, pass)) > 0) {
result = fmod((n / pow(10.0, pass)), 10.0);
cout << trunc(result);
pass = pass + 1;
}
cout << endl;
system("pause");
return 0;
}
This uses the methods (12345/10), which gives you 1234.5 which then truncates into 1234. The above code also use the modulo method ('%' is the operator for modulo). For example, if you do 12345 % 10, the program displays the remainder of 12345/10, which in this case, would be 5.
I used this method in a loop to get the desired output.
PLEASE NOTE THAT I MADE THIS PROGRAM FOR A CLASS, SO IF THIS IS NOT EXACTLY WHAT YOU ARE LOOKING FOR, KINDLY DISREGARD THIS POST.
Try this code-
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
float reversDigits(float num)
{
char buffer[20],ch,*ptr;
int i,j,len;
snprintf(buffer,20,"%.3lf",num);
len = strlen(buffer);
for(i=0,j=len-1;i<j;i++,j--)
{
ch=buffer[i];
buffer[i]=buffer[j];
buffer[j]=ch;
}
buffer[len] = '\0';
return atof(buffer);
}
int main()
{
float num = 45000.062;
printf("Reverse of no. is %.5lf\n", reversDigits(num));
return 0;
}
Am passing a number with 3 digits after ., so i am using %.3lf in snprintf, if you simply use %lf means, while converting it to string it will add zeros and some numbers. To avoid that am using, else you need to do a little bit of more work to remove it!
Note: while converting string to float else float to string, in decimal position it will add some extra number or zero. The programmer need to take care of it!
Related
I am writing a program to calculate the factorial of 100. The code is as below. Notwithstanding, the output is 0 as the answer is too big. Is there any answer to display the exact answer? This is because even unsigned long long is not even able to display the factorial of 100. Thank you.
#include <iostream>
using namespace std;
int main()
{
int n,i,fact=1;
cout << "enter the number "<<endl;
cin>>n;
for(i=1;i<=n;i++)
{
fact=fact*i;
}
cout<<"the factorial is "<<fact<<endl;
}
This is a rather simple task. We can do it like we would do it on a piece of paper. We use a std::vector of digits to hold the number. Because the result will be already too big for an unsigned long long for 22!.
The answer will be exact.
With such an approach the calculation is simple. I do not even know what to explain further.
Please see the code:
#include <iostream>
#include <vector>
int main()
{
std::cout << "Calculate n! Enter n (max 10000): ";
if (unsigned int input{}; (std::cin >> input) && (input <= 10000)) {
// Here we store the resulting number as single digits
std::vector<unsigned int> result(3000, 0); // Magic number. Is big enough for 100000!
result.back() = 1; // Start calculation with 1 (from right to left)
// Multiply up to the given input value
for (unsigned int count = 2; count <= input; count++)
{
unsigned int sum{}, remainder{};
unsigned int i = result.size() - 1; // Calculate from right to left
while (i > 0)
{
// Simple multiplication like on a piece of paper
sum = result[i] * count + remainder;
result[i--] = sum % 10;
remainder = sum / 10;
}
}
// Show output. Supporess leading zeroes
bool showZeros{ false };
for (const unsigned int i : result) {
if ((i != 0) || showZeros) {
std::cout << i;
showZeros = true;
}
}
}
else std::cerr << "\nError: Wrong input.";
}
Developed and tested with Microsoft Visual Studio Community 2019, Version 16.8.2.
Additionally compiled and tested with clang11.0 and gcc10.2
Language: C++17
You can use C++ Boost Library to to manipulate such large numbers.
Here is the code:
#include <bits/stdc++.h>
#include <boost/multiprecision/cpp_int.hpp>
using namespace std;
using namespace boost::multiprecision;
cpp_int fact(int);
int main(){
cpp_int a=1;
int n;
cin>>n;
cout<<fact(n)<<endl;
}
cpp_int fact(int x){
if(x==1)
return 1;
cpp_int temp=1;
temp= x*fact(x-1);
return temp;
}
I tried to build a function that calculates a binary number stored in a string into a decimal number stored in a long long. I'm thinking that my code should work but it doesn't.
In this example for the binary number 101110111 the decimal number is 375. But my output is completely confusing.
Here is my code:
#include <string>
#include <stdio.h>
#include <math.h>
#include <iostream>
#include <string.h>
int main() {
std::string stringNumber = "101110111";
const char *array = stringNumber.c_str();
int subtrahend = 1;
int potency = 0;
long long result = 0;
for(int i = 0; i < strlen(array); i++) {
result += pow(array[strlen(array) - subtrahend] * 2, potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
}
Here is the output:
1
99
9703
894439
93131255
9132339223
894974720087
76039722530902
8583669948348758
What I'm doing wrong here?
'1' != 1 as mentioned in the comments by #churill. '1' == 49. If you are on linux type man ascii in terminal to get the ascii table.
Try this, it is the same code. I just used the stringNumber directly instead of using const char* to it. And I subtracted '0' from the current index. '0' == 48, so if you subtract it, you get the actual 1 or 0 integer value:
auto sz = stringNumber.size();
for(int i = 0; i < sz; i++) {
result += pow((stringNumber[sz - subtrahend] - '0') * 2, potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
Moreover, use the methods provided by std::string like .size() instead of doing strlen() on every iteration. Much faster.
In a production environment, I would highly recommend using std::bitset instead of rolling your own solution:
std::string stringNumber = "1111";
std::bitset<64> bits(stringNumber);
bits.to_ulong();
You're forgetting to convert your digits into integers. Plus you really don't need to use C strings.
Here's a better version of the code
int main() {
std::string stringNumber = "101110111";
int subtrahend = 1;
int potency = 0;
long long result = 0;
for(int i = 0; i < stringNumber.size(); i++) {
result += pow(2*(stringNumber[stringNumber.size() - subtrahend] - '0'), potency);
subtrahend++;
potency++;
std::cout << result << std::endl;
}
}
Subtracting '0' from the string digits converts the digit into an integer.
Now for extra credit write a version that doesn't use pow (hint: potency *= 2; instead of potency++;)
c++ way
#include <string>
#include <math.h>
#include <iostream>
using namespace std;
int main() {
std::string stringNumber = "101110111";
long long result = 0;
uint string_length = stringNumber.length();
for(int i = 0; i <string_length; i++) {
if(stringNumber[i]=='1')
{
long pose_value = pow(2, string_length-1-i);
result += pose_value;
}
}
std::cout << result << std::endl;
}
I'm trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use of classes from the STL, although the program spec does say we can use "common C libraries" (gonna ask my professor if I can use cmath, because I'm assuming log10(num) + 1 is the easiest way, but I was wondering if there was another way).
Ah, and this doesn't have to handle negative numbers. Solely non-negative numbers.
I'm attempting to create a variant "MyInt" class that can handle a wider range of values using a dynamic array. Any tips would be appreciated! Thanks!
Not necessarily the most efficient, but one of the shortest and most readable using C++:
std::to_string(num).length()
The number of digits of an integer n in any base is trivially obtained by dividing until you're done:
unsigned int number_of_digits = 0;
do {
++number_of_digits;
n /= base;
} while (n);
There is a much better way to do it
#include<cmath>
...
int size = trunc(log10(num)) + 1
....
works for int and decimal
If you can use C libraries then one method would be to use sprintf, e.g.
#include <cstdio>
char s[32];
int len = sprintf(s, "%d", i);
"I mean the number of digits in an integer, i.e. "123" has a length of 3"
int i = 123;
// the "length" of 0 is 1:
int len = 1;
// and for numbers greater than 0:
if (i > 0) {
// we count how many times it can be divided by 10:
// (how many times we can cut off the last digit until we end up with 0)
for (len = 0; i > 0; len++) {
i = i / 10;
}
}
// and that's our "length":
std::cout << len;
outputs 3
Closed formula for the longest int (I used int here, but works for any signed integral type):
1 + (int) ceil((8*sizeof(int)-1) * log10(2))
Explanation:
sizeof(int) // number bytes in int
8*sizeof(int) // number of binary digits (bits)
8*sizeof(int)-1 // discount one bit for the negatives
(8*sizeof(int)-1) * log10(2) // convert to decimal, because:
// 1 bit == log10(2) decimal digits
(int) ceil((8*sizeof(int)-1) * log10(2)) // round up to whole digits
1 + (int) ceil((8*sizeof(int)-1) * log10(2)) // make room for the minus sign
For an int type of 4 bytes, the result is 11. An example of 4 bytes int with 11 decimal digits is: "-2147483648".
If you want the number of decimal digits of some int value, you can use the following function:
unsigned base10_size(int value)
{
if(value == 0) {
return 1u;
}
unsigned ret;
double dval;
if(value > 0) {
ret = 0;
dval = value;
} else {
// Make room for the minus sign, and proceed as if positive.
ret = 1;
dval = -double(value);
}
ret += ceil(log10(dval+1.0));
return ret;
}
I tested this function for the whole range of int in g++ 9.3.0 for x86-64.
int intLength(int i) {
int l=0;
for(;i;i/=10) l++;
return l==0 ? 1 : l;
}
Here's a tiny efficient one
Being a computer nerd and not a maths nerd I'd do:
char buffer[64];
int len = sprintf(buffer, "%d", theNum);
Would this be an efficient approach? Converting to a string and finding the length property?
int num = 123
string strNum = to_string(num); // 123 becomes "123"
int length = strNum.length(); // length = 3
char array[3]; // or whatever you want to do with the length
How about (works also for 0 and negatives):
int digits( int x ) {
return ( (bool) x * (int) log10( abs( x ) ) + 1 );
}
Best way is to find using log, it works always
int len = ceil(log10(num))+1;
Code for finding Length of int and decimal number:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int len,num;
cin >> num;
len = log10(num) + 1;
cout << len << endl;
return 0;
}
//sample input output
/*45566
5
Process returned 0 (0x0) execution time : 3.292 s
Press any key to continue.
*/
There are no inbuilt functions in C/C++ nor in STL for finding length of integer but there are few ways by which it can found
Here is a sample C++ code to find the length of an integer, it can be written in a function for reuse.
#include<iostream>
using namespace std;
int main()
{
long long int n;
cin>>n;
unsigned long int integer_length = 0;
while(n>0)
{
integer_length++;
n = n/10;
}
cout<<integer_length<<endl;
return 0;
}
Here is another way, convert the integer to string and find the length, it accomplishes same with a single line:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
long long int n;
cin>>n;
unsigned long int integer_length = 0;
// convert to string
integer_length = to_string(n).length();
cout<<integer_length<<endl;
return 0;
}
Note: Do include the cstring header file
The easiest way to use without any libraries in c++ is
#include <iostream>
using namespace std;
int main()
{
int num, length = 0;
cin >> num;
while(num){
num /= 10;
length++;
}
cout << length;
}
You can also use this function:
int countlength(int number)
{
static int count = 0;
if (number > 0)
{
count++;
number /= 10;
countlength(number);
}
return count;
}
#include <math.h>
int intLen(int num)
{
if (num == 0 || num == 1)
return 1;
else if(num < 0)
return ceil(log10(num * -1))+1;
else
return ceil(log10(num));
}
Most efficient code to find length of a number.. counts zeros as well, note "n" is the number to be given.
#include <iostream>
using namespace std;
int main()
{
int n,len= 0;
cin>>n;
while(n!=0)
{
len++;
n=n/10;
}
cout<<len<<endl;
return 0;
}
i am learning recursion in C++ and as practice i was trying to write binary to decimal converter with recursive function. In following code converter is working as it should:
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int sum = 0;
int DecimalConversion (int power, int number){
int bit;
if (number == 0)
{
return 0;
}
bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
DecimalConversion(power, number);
return sum;
//return bit * pow(2, power) + DecimalConversion(power, number);
}
int main(){
int power = 0;
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(power, number);
system("PAUSE >> NULL");
return 0;
}
Is it possible to return value from DecimalCoonversion function by not using global variable? Can someone explain how, I tried next line of code but it does not work correctly:
return bit * pow(2, power) + DecimalConversion(power, number);
Can anyone explain where i am making mistake using previous line of code?
Thank You in advance
This adds sum as a parameter to your function, but makes it default to 0 if you don't provide it explictly. Power is also defaulted to 0, which saves you having to pass it into the function.
Since default parameters must be at the end of a function declarations and/or definitions parameter list, I had to move power across to achieve this.
#include <iostream>
#include <cmath>
#include <bitset>
using namespace std;
int DecimalConversion (int number, int power = 0, int sum = 0) // changes here
{
if (number == 0)
{
return sum;
}
int bit = number % 10;
sum = sum + bit * pow(2, power);
number /= 10;
power++;
return DecimalConversion(number, power, sum); // changes here
}
int main(){
int number = 0;
cout << "Enter binary number: " << endl;
cin >> number;
cout << "Number is: " << DecimalConversion(number);
system("PAUSE >> NULL");
return 0;
}
Please note I didn't check this actually converts binary to decimal correctly, just that the recursion works.
You can call this function like so:
DecimalConversion(number);
This:
int DecimalConversion(int power, int number){
if (number == 0)
return 0;
else
return (number % 10)*pow(2, power) + dc(power+1, number/10);
}
or
int DecimalConversion(int power, int number){
return number?(number % 10)*pow(2, power) + dc(power+1, number/10):0;
}
I decided to implement addition using strings, as my numbers may be huge. The problem that I'm facing is how to convert from decimal numbers in strings to binary. If lol is the result of an addition, I'm trying to convert it to a binary form using:
unsigned long long function_arg = atoi( lol.c_str() );
As the number of digits grows, as for example n>14, it fails, so even long long is too short. What can you advise me to do? Here is actually the code of my program (working with decimal system):
#include <iostream>
#include <string>
#include <bitset>
#include <conio.h>
using namespace std;
string add (string &s1, string &s2) {
int carry=0,sum,i;
string min=s1,
max=s2,
result = "";
if (s1.length() > s2.length()) {
max = s1;
min = s2;
} else {
max = s2;
min = s1;
}
for (i = min.length()-1; i>=0; i--) {
sum = min[i] + max[i + max.length() - min.length()] + carry - 2*'0';
carry = sum/10;
sum %=10;
result = (char)(sum + '0') + result;
}
i = max.length() - min.length()-1;
while (i>=0) {
sum = max[i] + carry - '0';
carry = sum/10;
sum%=10;
result = (char)(sum + '0') + result;
i--;
}
if (carry!=0) {
result = (char)(carry + '0') + result;
}
return result;
}
string Dex_To_bin(unsigned long long number){
string result;
unsigned long long bitmask = 1ULL << 63;
do
result.push_back(static_cast<bool>(number & bitmask));
while (bitmask >>= 1);
return result;
}
int main () {
string a,b;
cin >> a >> b;
add(a,b);
cout << add(a,b) << endl;
cout << endl;
cout << endl;
string lol=add(a,b);
unsigned long long funtion_arg = atoi( lol.c_str() );
cout << Dex_To_bin(funtion_arg) << bitset<64>(funtion_arg) << endl;
cin.get();
cin.ignore();
getch();
return 0;
}
Function add works great, the problem is with Dec_to_Bin :(
You're using strings to represent very long numbers, right? Numbers that won't fit into standard numeric types? The result is no different. Think of making a set of functions that take numbers-represented-as-strings. That's the only way they're allowed to deal with the numbers.
So, write your decimal-to-binary function to take the string directly, and convert one digit of the string at a time.
What can you advise me to do?
Don't. A large value can't be converted to a type that is too small. You don't need this method at all in your API, or at least you shouldn't.
BTW the method signature you have devised doesn't make sense. The parameter should have been a 'string', and the result should have been a 'long long'. But don't provide it.