Remove digits from a number in Java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How do I remove the first digit of an integer?
My input is an integer (for example i = 123456789).
I then want to remove the first digit, so that i equals 23456789.

try this
n = n % (int) Math.pow(10, (int) Math.log10(n));

Here is one way to do it:
Convert it to String
Take the substring without the first "digit"
Convert it to int
Code:
public static void main(String[] args)
{
int x = 123456789;
String x_str = Integer.toString(x);
int new_x = Integer.parseInt(x_str.substring(1));
System.out.println(new_x);
}
Output:
23456789
Note: This can be done in one line with
int x = 123456789;
int new_x = Integer.parseInt(Integer.toString(x).substring(1));
Edit:
To handle negative-case, check if number is positive or integer:
int new_x = Integer.parseInt(x > 0 ?
Integer.toString(x).substring(1) : Integer.toString(x).substring(2));

If you want to avoid the string conversion, you can find the high digit and subtract it.
public static void main(String[] args) {
int x = 123456789;
System.out.println("x = " + x);
int hi = x, n = 0;
while (hi > 9) {
hi /= 10;
++n;
}
for (int i = 0; i < n; i++) hi *= 10;
x -= hi;
System.out.println("x with high digit removed = " + x);
}

Here's the one-line, purely numeric solution:
i %= (int) Math.pow(10, (int) Math.log10(i));

Alternate approach:
int stripLeading(int i) {
if(i > 0) {
return i - (int)Math.pow(10, (int)Math.log10(i));
} else if(i > 0) {
return i + (int)Math.pow(10, (int)Math.log(-i+1));
} else {
return 0;
}
}

I think I remember the string-free version of this … although I totally agree with #Christian as how I would do it…
NOTE: as #Darren Gilroy pointed out, one must consider negatives and zero spocially, and my function fails to do so.
Of course % is a better solution also.
public static void main (String [] argv)
{
final int x = 123456789;
int newX = x;
/* How many digits are there? */
final double originalLog = Math.floor (Math.log10 (x));
/* Let's subtract 10 to that power until the number is smaller */
final int getRidOf = (int)Math.pow (10, originalLog);
while (originalLog == Math.floor (Math.log10 (newX)))
{ newX -= getRidOf; }
System.out.println (newX);
}
Poor profiling attempt:
Looping the above function without the println for 20,000,000,000 repeats in a for loop:
real 0m9.943s
user 0m9.890s
sys 0m0.028s
The same with Christian's far-easier-to-understand and perfectly functionable version, but for only 200,000,000 repeats (because I'm lazy and got tired of waiting):
real 0m18.581s
user 0m17.972s
sys 0m0.574s
So one might argue that constructing the String objects is probably slowing it down by roughly 200×, but that isn't a really finely-tuned profiling set-up.

If you want to go for simpler methods and without using String, then here's my simple take:
Count number of digits int the integer.
Divide the int by 10^n. n is the number of digits.
Obtain absolute value of the result. //In case of (-)ve numbers.
For example
int i = 123456789;
int n = getDigitCount(i);
int r = Math.abs(i / (int)Math.pow(10,n)); //r stores result.
And you'd require this method:
int getDigitCount(int num)
{
int c = 0;
while(num > 0){
num/=10;
c++;
}
return c;
}

Related

What is wrong of my solution for the Leetcode question Sqrt(x)?

I am trying Leetcode Question - 69. Sqrt(x)
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.
class Solution {
public int mySqrt(int x) {
int ans = 0;
int i=1;
while(i*i<=x){
ans = i;
i++;
}
return ans;
}
}
This is the code I came up with. But the testcase input=2147395600 is not passing.
My Output = 289398
Expected Output = 46340
I'm confused as I have put the condition i*i<=x, then how can ans be more than the sqrt value?
Since you are comparing i * i with the input x, if the input x is too close to Integer.MAX_VALUE (2.147.483.647), like in that test case, i * i will be bigger than the maximum value allowed for an int to have and i*i<=x will be true.
Possible solutions:
Implement a binary search algorithm where max would be the floor(sqrt(Integer.MAX_VALUE)) or 46340.
Implement a algorithm where ans, i and x are declared locally as long type variables and in the return line you return the value cast to int using return (int)ans;
By running the following algorithm you can see the limit of a java int exploding and what happens afterwards.
int x = 2;
while(true) {
System.out.println(x);
x *= 2;
}
Not pretending to be fast, just the idea that (n+1)2=n2 + 2n + 1:
public static int mySqrt(int x) {
int i = 0;
while (x >= 0) {
x -= (i++ << 1) + 1;
}
return i - 1;
}
My JavaScript Solution
var mySqrt = function(x) {
var ans = 1;
if(x === 0){
ans = 0;
} else {
for (let i = 1; i< x;i++){
if(i*i === x){
ans = i;
break;
}
if(i*i >x){
ans = i - 1;
break;
}
}
}
return ans;
};

Rounding integers to one significant digit

I want to round down an int in Java, what i mean is, if I have an int 45678, i want to convert that int into 40000
this is how im calling it
int den = placeValue(startCode,length);
and this is the code
static int placeValue(int N, int num)
{
int total = 1, value = 0, rem = 0;
while (true) {
rem = N % 10;
N = N / 10;
if (rem == num) {
value = total * rem;
break;
}
total = total * 10;
}
return value;
}
so if i have 89765, i would want 80000,
but instead it return the place value of whatever length is.
So,
for 89765, the length would be 5, so the return value is 5 i.e. the value in the ones place.
but if the number was 85760
then it would return 5000.
I hope that makes sense.
Any suggestions would be much appreicated.
In my opinions, if I can avoid 'calculating' I will compute the answer from other concept since I am not confidence on my math (haha).
Here is my answer. (only work in positive numbers)
I think the length of the inputted number is not necessary.
static int placeValue2(int N) {
String tar = N+"";
String rtn = tar.substring(0,1); // take first digital
for (int i=0;i<tar.length()-1;i++) // pad following digitals
rtn+="0";
return Integer.parseInt(rtn);
}
I appreciate you asked the question here.
Here is my solution. I don't know why you are taking two parameters, but I tried it from one param.
class PlaceValue{
int placeValue(int num){
int length = 0; int temp2=1;
boolean result=false;
long temp1=1;
if (num<0){
result=true;
num=num*(-1);
}
if (num==0){
System.out.println("Value 0 not allowed");
return 0;
}
while (temp1 <= num){ //This loop checks for the length, multiplying temp1 with 10
//untill its <= number. length++ counts the length.
length++;
temp1*=10;
}
for (int i=1; i<length; i++){//this loop multiplies temp2 with 10 length number times.
// like if length 2 then 100. if 5 then 10000
temp2=temp2*10;
}
temp2=(num/temp2)*temp2;
/* Let's say number is 2345. This would divide it over 1000, giving us 2;
in the same line multiplying it with the temp2 which is same 1000 resulting 2000.
now 2345 became 2000;
*/
if (result==true){
temp2=temp2*(-1);
}
return temp2;
}
}
Here is the code above. You can try this. If you are dealing with the long numbers, go for long in function type as well as the variable being returned and in the main function. I hope you understand. otherwise, ask me.
Do you want something like this?
public static int roundDown(int number, int magnitude) {
int mag = (int) Math.pow(10, magnitude);
return (number / mag) * mag;
}
roundDown(53278,4) -> 50000
roundDown(46287,3) -> 46000
roundDown(65478,2) -> 65400
roundDown(43298,1) -> 43290
roundDown(43278,0) -> 43278
So the equivalent that will only use the most significant digit is:
public static int roundDown(int number) {
int zeros = (int) Math.log10(number);
int mag = (int) Math.pow(10, zeros);
return (number / mag) * mag;
}

C(n,r) calculator program doesn't work

I made a C(n,r) calculator using java Netbeans JFrameform.
here is the frame
Here is the code :-
private void lllActionPerformed(java.awt.event.ActionEvent evt) {
int n=Integer.parseInt(t1.getText());
int r=Integer.parseInt(t2.getText());
int s=1;
for(int i=1;i<=n;i=i+1){
s=i*s;
}
int p=1;
for(int j=1;j<=n-r;j=j+1){
p=j*p;
}
int q=1;
for(int k=1;k<=r;k=k+1){
q=k*q;
}
int re=s/(p*q);
t3.setText(" "+re);
}
the code works well for values values of n upto 12. But for 13 and onward , code starts giving wrong answer.
wrong output
why is this happening? Your help is appreciated.
During the calculations the value goes over Integer.MAX_VALUE This is an overflow of arithmetic operation:
Integer overflow can be demonstrated through an odometer overflowing, a mechanical version of the phenomenon. All digits are set to the maximum 9 and the next increment of the white digit causes a cascade of carry-over additions setting all digits to 0, but there is no higher digit to change to a 1, so the counter resets to zero. This is wrapping in contrast to saturating.
In computer programming, an integer overflow occurs when an arithmetic operation attempts to create a numeric value that is outside of the range that can be represented with a given number of bits – either larger than the maximum or lower than the minimum representable value.
Try to replace int with long values. It will work with a greater value.
private void lllActionPerformed(java.awt.event.ActionEvent evt) {
int n=Integer.parseInt(t1.getText());
int r=Integer.parseInt(t2.getText());
int s=1;
for(int i=1;i<=n;i=i+1){
s=i*s;
}
long p=1L;
for(int j=1;j<=n-r;j=j+1){
p=j*p;
}
long q=1L;
for(int k=1;k<=r;k=k+1){
q=k*q;
}
long re=s/(p*q);
t3.setText(" "+re);
}
With 14 and 2 as inputs the result is 91.
If you want to have a correct result for big values you have to use a BigInteger that handle:
Immutable arbitrary-precision integers
Try using this
private void lllActionPerformed(java.awt.event.ActionEvent evt) {
int n=Integer.parseInt(t1.getText());
int r=Integer.parseInt(t2.getText());
if (r > n / 2) r = n - r; // because C(n, r) == C(n, n - r)
long ans = 1;
int i;
for (i = 1; i <= r; i++) {
ans *= n - r + i;
ans /= i;
}
t3.setText(" "+ans);
}

Java output issue? Program not getting desired result [format updated] [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
This program is supposed to go through the number of 2 to 50 people and get the probability out of 100,000 trials whether 2 people will have the same birthday or not.
import java.util.Random;
public class birthday {
public static void main(String[] args) {
int N = 2;
while (N != 51) {
double probability = one_probability(N);
System.out.println(N + " " + probability);
N++;
}
}
public static boolean one_group(int N) {
int A[] = new int[N];
Random random = new Random();
boolean have_match = false;
for (int i = 0; i < N; i++) { //assigns each person a birthday
int k = random.nextInt(365);
A[i] = k;
}
for (int i = 0; i < N; i++) { //testing to see if birthdays match up
for (int j = i+1; j < N; j++) {
if (A[i] == A[j]) { have_match = true; break; }
}
}
return have_match;
}
public static double one_probability(int N) {
int x = 0;
for (int i = 0; i < 100000; i++) { //repeating 100,000 times to get average probability
boolean have_match = one_group(N);
if (have_match == true) { x++; }
}
double probability = x / 100000; //getting the average probability
return probability;
}
}
Here's the result (it goes from 2-50), it keeps giving me zeros so I know something is wrong. Please help :)
Output
Try with
int probability = x / 1000; // 1/100 of the value to get an probability in percent (integer)
or
float probably = x / 100000F; //F for a `float`
double probability = x / 100000.0; //a decimal without a F is a `double`
Without that, this can't work :
float probably = x / 100000;
First, the division of two integer will be stored in memory like an integer then store in a float/double. That storage truncate the value. This is the operator logic to return the biggest type in an operation so :
int * int -> int
int * float -> float
int * double -> double
short * short -> int //that's a trick, int is the minimal value an operation can return
int probability=x/100000; always return 0.
convert it to double probability=x/100000.0; the value of probability will always less than or equal one. because x will never be greater than 100000. And also change the return type of one_probability method to double.

How to swap digits in java

I am trying to practice java over the summer and i'm stuck on this problem. I need to swap the 2 letters in a integer in java. For example in my main method I make a method called swapdigits and have my parameters as 1432. The program should swap the 4 and 1 and 3 and 2. The output should be 4123 since it swapped the two letters in order. Lets say I do swapdigits(1341234) the output should be 3114324. I know I have to use while loops but i'm getting stuck on the swapping.
This is what I have so far:
public static void main(String[] args) {
Swapdigits(2413);
}
public static void Swapdigits(int number){
while(number>0){
int y=number/1000;
int x=number%10;
int original=number-y;
System.out.println(original);
}
System.out.println();
}
}
public static int swapDigitPairs(int number) {
int result = 0;
int place = 1;
while (number > 9) {
result += place * 10 * (number % 10);
number /= 10;
result += place * (number % 10);
number /= 10;
place *= 100;
}
return result + place * number;
}
You can also try
char[] a = String.valueOf(number).toCharArray();
for (int i = 0; i < a.length - 1; i += 2) {
char tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
}
int number = Integer.parseInt(new String(a));
Because you're just swapping the places of digits, it doesn't actually matter what the number is. So, it's probably easier (and makes more sense) to represent the argument as a string. That way you aren't dealing with weird modulo operators - If you were solving the problem by hand, would you actually do any math? You'd treat this problem the same whether it were numbers of a bunch of characters.
Take a look at the following question for information on swapping characters in a String:
How to swap String characters in Java?

Categories

Resources