Convert base 10 into a certain base [duplicate] - c++

This question already has answers here:
Converting numbers between Number Bases
(4 answers)
Closed 7 years ago.
I have a problem.
I want to convert an integer (ex 64) into a certain base (ex 4). The number would look like 100 ( I think ).
I need to get the number as presented before ( 100 ).
If I use the algorithm I thought of I will get 001 which will be transformed into 1. How can I convert the base 10 integer into a base 4 representation starting with the first digit that is not 0.
Sorry for my bad explanation, I hope somebody will understand.
int x=64;
int t=x; // temp variable
int pp=0;
int base=4;
while(t!=0)
{
pp = pp * 10 + t%base;
t/=base;
}

You need to add the data to the front of your value:
int x = 64;
int t = x; // temp variable
int pp = 0;
int base = 4;
int pos = 1;
while (t != 0)
{
pp += (t % base) * pos;
t /= base;
pos *= 10;
}
I hope you only use this for playing around as there are a lot of traps you could fall in (e.g. if base is less than 0 or more than 10)

Related

Problem with Reversing Large Integers On Leetcode?

I was working on this problem from Leetcode where it has this requirement of reversing numbers whilst staying within the +/-2^31 range. I checked out other solutions made for this problem, and from there created my own solution to it. It worked successfully for numbers ranging from 10 to less than 99,999,999. Going more than that(when trying to submit the code to move to the next question) would throw an error saying:
"Line 17: Char 23: runtime error: signed integer overflow: 445600005 * 10 cannot be represented in type 'int' (solution.cpp)"
This was the input given when trying to submit the code: 1534236469
My code
class Solution {
public:
int reverse(int x) {
int flag = 0;
int rev = 0;
if (x >= pow(2, 31)) {
return 0;
} else {
if (x < 0) {
flag = 1;
x = abs(x);
}
while(x > 0) {
rev = rev * 10 + x % 10;
x /= 10;
}
if (flag == 1) {
rev = rev*(-1);
}
return rev;
}
}
};
As you can see from my code, I added an if statement that would basically return 0 if the number was greater than 2^31. Unfortunately, this was wrong.
Can anyone explain how this can be fixed? Thank you in advance.
Problem statement asks to return 0 if reversed number does not belong to integer range :
If reversing x causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then return 0.
In your code you checked if input fits in integer range but their arises a corner case when the integer has 10 digits and last digit is >2 (and for some cases 2).
Lets consider the input 1534236469: 1534236469 < 2^31 - 1
so program executes as expected now lets trace last few steps of program execution : rev = 964632435 and x = 1 problem arises when following statement is executed :
rev = rev * 10 + x % 10;
Now, even though input can be represented as integer rev * 10 i.e. 9646324350 is greater than integer range and correct value that should be returned is zero
Fix ?
1. Lets consider 10 digit case independently
Even though this can be done, it gives rise to unnecessary complications when last digit is 2
2. Make rev a long integer
This works perfectly and is also accepted, but sadly this is not expected when solving this problem as statement explicitly asks to not use 64-bit integers
Assume the environment does not allow you to store 64-bit integers (signed or unsigned).
3. Checking before multyplying by 10 ?
This works as expected. Before multyplying rev by 10 check if it is >= (pow(2,31)/10)
while(x > 0) {
if (rev >= pow(2, 31)/10 )
return 0;
rev = rev * 10 + x % 10;
x /= 10;
}
I hope this solves your doubt !! Comment if you find something wrong as this is my first answer.
Note : The following if statement is unnecessary as input is always a 32-bit integer
Given a signed 32-bit integer x
if (x >= pow(2, 31)) {
return 0;
}
Edit : As most of the comments pointed it out, instead of pow(2,31), use INT_MAX macro as it suffices here.
public static int reverse(int x) {
boolean isNegative = false;
if (x < 0) {
isNegative = true;
x = -x;
}
long reverse = 0;
while (x > 0) {
reverse = reverse * 10 + x % 10;
x=x/10;
}
if (reverse > Integer.MAX_VALUE) {
return 0;
}
return (int) (isNegative ? -reverse : reverse);
}

I need to get a random number in the range from a to b with n decimal places

I need a function that returns me a random number with n decimal places
Example:
int aleatorio(int li, int ls)
{
return rand()%(ls+1-li)+li;
}
What i want is:
float new_random(int start, int final, int number_decimals)
{
return // What should I write here?
}
if I would call this function 5 times like this::
new_random(0, 5, 4);
The exit would be:
0.2344
3.4356
2.8435
4.2435
I do not want to use this, because I need numbers of 4 exact decimal places since I will not use them to print, but you will have others:
cout << setprecision(4) << 4.24359675967 << endl; //I do not want this
I need numbers of 4 exact decimal places
Then you cannot use finite precision binary floating point (i.e. float, double or long double) because those types cannot exactly represent all of the values with 4 decimal places.
A solution is to use arbitrary precision floating point, and another is to use fixed point. C++ standard doesn't provide arbitrary precision types nor fixed point types. Another approach is to give up the requirement of exactly representing those values and accept the almost exact values that are achievable with limited precision.
Try this for a Java solution. Multiply the start and finish by 1000, generating ints between the range and then divide the resultant number by 1000 as a double.
int start = 20;
int finish = 30;
int count = 10;
Random r = new Random();
r.ints(start * 1000, finish * 1000).filter(n -> n % 10 != 0)
.limit(count).mapToDouble(n -> n / 1000.)
.forEach(System.out::println);
prints something like this.
21.186
26.983
25.345
20.764
27.911
21.139
24.679
27.722
29.443
28.675
Or as a method supplying the starting number, ending number and precision.
for (int i = 0; i < 10; i++) {
System.out.println(newRandom(start,finish,4));
}
static Random r = new Random();
public static Double newRandom(int start, int finish, int precision) {
int f = (int)Math.pow(10,precision);
return r.ints(start * f, finish * f).filter(n -> n % 10 != 0)
.limit(1).mapToDouble(n -> n / (double)f).findFirst().getAsDouble();
}
Prints something like this.
28.4444
25.0259
29.5611
25.6445
25.4977
28.5124
28.9709
23.4835
27.9766
23.9438
You can generate an integer number N between start and final * 10^number_decimals and then return N / 10^number_decimals
Eg. start = 0, final = 5, number_decimals = 4 ==> N in [0 - 50000] ==> N/10000 in [0.0000 - 5.0000]
float new_random(int start, int final, int number_decimals) {
return aleatorio(start, final*pow10(number_decimals))/number_decimals;
}
You can define pow10 as:
int pow10(int p) {
if (p == 0) return 1;
else return 10 * pow10(p-1);
}

How do I get the number of a specific place in an int in C++?

So I have an int that counts upwards.
Let's say we're up to 65,000 already.
I need to get the number in the thousandth place (the 5), to be assigned to another int.
I found the following snippet which is pretty easy but not quite what I need.
You can use % operator for any number of integers you want to
separate. For example 888881%10 will give you 1 and 888881%100 will
give you 81...
Thanks!
You probably need this.
int AtPos(int number, int pos)
{
return ((number > 0 ? number : -number) / (int)pow(10, pos)) % 10;
}
If this is that you are looking for, arguments validity check should be added.
EDIT.
I just noticed, you need to assign different number in specified position. So you need this improvement:
int& SetValueAtPos(int& number, int pos, int newValue)
{
int power = (int)pow(10, pos);
number -= AtPos(number, pos) * power;
number += power * newValue;
return number;
}
Additionally you can merge those functions and cache value of pow(10, pos) so it would be more optimal.
Try something like this
int a =65432;
int b = ((a%10000)-(a%1000))/1000;
here (a%10000) = 5432
and (a%1000) = 432
so (a%10000)-(a%1000) will be 5000
and finally 5000/1000 = 5
or directly you can use
int b = (a%10000)/1000;
What #Matt suggested in comment is:
int num1 = 65000;
int num2 = num%10000; //num2 is 5000
num2 = num2/1000;
Output: 5

Why does trunc(1) output as 0?

Can someone explain me why in c++ happens such a thing:
double tmp;
... // I do some operations with tmp
// after which it has to be equal to one
cout << tmp; // prints 1
cout << trunc(tmp); // prints 0
cout << trunc(tmp*10); // prints 9
I am using this for separation part right of decimal part from the number for example if i have: 5.010 ... i want to have 0.010 .. so I am using:
double remainder = tmp - trunc(tmp);
I am posting the whole code....the suggestion with floor does not worked
short getPrecision(double num, short maxPrecision) {
// Retrieve only part right of decimal point
double tmp = fabs(num - trunc(num));
double remainder = tmp;
// Count number of decimal places
int c = 0;
while (remainder > 0 && c < maxPrecision) {
tmp *= 10;
remainder = tmp - trunc(tmp);
c++;
}
return c;
}
When I run this function for example with 5.1 the remanider is 0 instead of 1
After some calculations it has to be one? Well, it could as well be 0.99999999999999999. Floating point operations are not precise, you should always take that into account.
Please see picture at http://en.cppreference.com/w/cpp/numeric/math/trunc. The chart there explains the inconsistency with truncing 1. Probably the same applies to 10 as well
This should help you achieving what you need:
double remainder = tmp - floor(tmp);

Finding a Specific Digit of a Number

I'm trying to find the nth digit of an integer of an arbitrary length. I was going to convert the integer to a string and use the character at index n...
char Digit = itoa(Number).at(n);
...But then I realized the itoa function isn't standard. Is there any other way to do this?
(number/intPower(10, n))%10
just define the function intPower.
You can also use the % operator and / for integer division in a loop. (Given integer n >= 0, n % 10 gives the units digit, and n / 10 chops off the units digit.)
number = 123456789
n = 5
tmp1 = (int)(number / 10^n); // tmp1 = 12345
tmp2 = ((int)(tmp1/10))*10; // tmp2 = 12340
digit = tmp1 - tmp2; // digit = 5
You can use ostringstream to convert to a text string, but
a function along the lines of:
char nthDigit(unsigned v, int n)
{
while ( n > 0 ) {
v /= 10;
-- n;
}
return "0123456789"[v % 10];
}
should do the trick with a lot less complications. (For
starters, it handles the case where n is greater than the number
of digits correctly.)
--
James Kanze
Itoa is in stdlib.h.
You can also use an alternative itoa:
Alternative to itoa() for converting integer to string C++?
or
ANSI C, integer to string without variadic functions
It is also possible to avoid conversion to string by means of the function log10, int cmath, which returns the 10th-base logarithm of a number (roughly its length if it were a string):
unsigned int getIntLength(int x)
{
if ( x == 0 )
return 1;
else return std::log10( std::abs( x ) ) +1;
}
char getCharFromInt(int n, int x)
{
char toret = 0;
x = std::abs( x );
n = getIntLength( x ) - n -1;
for(; n >= 0; --n) {
toret = x % 10;
x /= 10;
}
return '0' + toret;
}
I have tested it, and works perfectly well (negative numbers are a special case). Also, it must be taken into account that, in order to find tthe nth element, you have to "walk" backwards in the loop, subtracting from the total int length.
Hope this helps.
A direct answer is:
char Digit = 48 + ((int)(Number/pow(10,N)) % 10 );
You should include the <math> library
const char digit = '0' + number.at(n);
Assuming number.at(n) returns a decimal digit in the range 0...9, that is.
A more general approach:
template<int base>
int nth_digit(int value, int digit)
{
return (value / (int)pow((double)base, digit)) % base;
}
Just lets you do the same thing for different base numbers (e.g. 16, 32, 64, etc.).
An alternative to itoa is the std::to_string method. So, you could simply do:
char digit = to_string(number)[index]