I need to define the last digit of a number assign this to value.
After this, return the last digit.
My snippet of code doesn't work correctly...
Code:
public int lastDigit(int number) {
String temp = Integer.toString(number);
int[] guess = new int[temp.length()];
int last = guess[temp.length() - 1];
return last;
}
Question:
How to solve this issue?
Just return (number % 10); i.e. take the modulus. This will be much faster than parsing in and out of a string.
If number can be negative then use (Math.abs(number) % 10);
Below is a simpler solution how to get the last digit from an int:
public int lastDigit(int number) { return Math.abs(number) % 10; }
Use
int lastDigit = number % 10.
Read about Modulo operator: http://en.wikipedia.org/wiki/Modulo_operation
Or, if you want to go with your String solution
String charAtLastPosition = temp.charAt(temp.length()-1);
No need to use any strings.Its over burden.
int i = 124;
int last= i%10;
System.out.println(last); //prints 4
Without using '%'.
public int lastDigit(int no){
int n1 = no / 10;
n1 = no - n1 * 10;
return n1;
}
You have just created an empty integer array. The array guess does not contain anything to my knowledge. The rest you should work out to get better.
Your array don't have initialization. So it will give default value Zero.
You can try like this also
String temp = Integer.toString(urNumber);
System.out.println(temp.charAt(temp.length()-1));
public static void main(String[] args) {
System.out.println(lastDigit(2347));
}
public static int lastDigit(int number)
{
//your code goes here.
int last = number % 10;
return last;
}
0/p:
7
Use StringUtils, in case you need string result:
String last = StringUtils.right(number.toString(), 1);
Another interesting way to do it which would also allow more than just the last number to be taken would be:
int number = 124454;
int overflow = (int)Math.floor(number/(1*10^n))*10^n;
int firstDigits = number - overflow;
//Where n is the number of numbers you wish to conserve</code>
In the above example if n was 1 then the program would return: 4
If n was 3 then the program would return 454
here is your method
public int lastDigit(int number)
{
//your code goes here.
int last =number%10;
return last;
}
Although the best way to do this is to use % if you insist on using strings this will work
public int lastDigit(int number)
{
return Integer.parseInt(String.valueOf(Integer.toString(number).charAt(Integer.toString(number).length() - 1)));
}
but I just wrote this for completeness. Do not use this code. it is just awful.
Related
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;
}
I am a beginner in Java and trying to learn. I have an integer from whom I want to calculate the double of each digit and then restore the answer in the integer. I think that I have to use the for() loop and tempvalue. I have the number 1234 and I need to get 2468.
I did this and I got 1234. Can someone find the issue, I am not very good with the index concept.
public class Doublevalue {
public static void main(String[] args) {
num=1234;
for(int i=0;num<0;i++) {
int tempvalue=(num%10*2)/10;
num=tempvalue;
System.out.print(num);
}}}
Because doubling digits is only valid when every digit is less than 5, the solution can be just
num *= 2;
But if you want the treat each digit separately, you need to do something like this:
int tmp = 0;
for (int column = 1; num > 0; column *= 10) {
tmp += (num % 10) * column * 2;
num /= 10;
}
num = tmp;
See live demo.
You can do an in-place replacement of each digit, but the logic is a little more complicated.
The code you currently provided has everything right - except for what you are doing in the loop.
In your example, you are executing int tempvalue=(num%10*2)/10;. I'm pretty certain that you are not sure what you are doing. What the line is doing is getting the remainder of the number when it is divided by 10, multiplying it by 2, then dividing by then. I can't seem to understand why you are doing this, so I will provide my own solution.
public class DoubleDigits {
public static void main(String[] args) {
DoubleDigits dd = new DoubleDigits();
System.out.println(dd.doubleDigits(1234));
}
public int doubleDigits(int number) {
StringBuilder str = new StringBuilder();
String testCase = String.valueOf(number);
for(int i = 0; i < testCase.length(); i++) {
int digit = Integer.parseInt(String.valueOf(testCase.charAt(i)))*2;
str.append(digit);
}
return Integer.parseInt(str.toString());
}
}
So what's happening?
First, we convert the number to a String, so we can get each single character (as a number). The for loop will loop through every single character, and we can use a StringBuilder to append the character after it has been parsed to an int and multiplied by two.
In the above example, the program produces:
2468
When the test case is:
1234
And when the test case is:
9999
The result is:
18181818
I have an integer in java. How do I replace its’ first three numbers with 111(or any other number), for example turning 783729 into 111729?
Many thanks!
You could convert it into a string and then replace the first three letters.
String s = String.valueOf(783729);
int i = Integer.parseInt(s.replace(s.substring(0, 3), "111"));
Convert the integer to string replace the first three characters and convert it back to integer.kindly try to do it yourself. if you feel stuck during coding post your code along with the problem you face.
You can do this without converting to a string using simple arithmetic:
// Assumes that num is initially at least 999.
int replaceWith111(int num) {
if (num < 1000) {
return 111;
}
return 10 * replaceWith111(num / 10) + (num % 10)
}
Obviously if you just need to get this done you'd convert to String and do the substitution there.
However, just for fun, here's how you could do it using only Math functions and operators. Doesn't handle negative numbers - that's left as an exercise fo the reader :)
int s = 111;
int n = 783729;
int ds = (int)Math.ceil(Math.log10(s));
int dn = (int)Math.ceil(Math.log10(n));
int b = (int)Math.pow(10, dn-ds);
int sn = s * b + n % b;
System.out.println(sn);
Output:
111729
My method seems to only work for all int less than 2^10. If it is greater than or equal to this value then it just returns 2^32. I'm not sure how my program is even getting this. I need to make it work for all int less than or equal to 2^15. Can anybody at least see why it's returning 2^32 for int greater than or equal to 2^10? If so then let me know please.
public static int DecToBin(int num) {
int binNum = 0;
int divisor = num;
int mod = 0;
int exp =0;
while(divisor != 0){
mod = divisor%2;
divisor = divisor/2;
if(mod==1){
binNum = (int) (binNum + (Math.pow(10, exp)));
}
exp++;
}
return binNum;
}
An always easy way to accomplish this is:
Integer.toBinaryString(int);
This is the easiest way to do this but their might be more efficiant ways to do it.
Hopefully this is what you were looking for
As Taco pointed out, you can call Integer.toBinaryString(int), but if this is for an assignment or something where you should write the method yourself, here is what I would do.
I would write a method, that will constantly divide the number by 2, and store the remainders in a String. Something like this:
String binaryString = "";
int value = 100;
while(value > 0){
int remainder = value % 2;
value = value/2;
binaryString = remainder + binaryString;
}
I tested this in a quick console run and it produced '1100100' which is correct.
EDIT I used this as a reference.
So I need to develop a method to find the smallest digit in an integer.
Here is my implementation
public int find(int n){
if(n < 10) return n;
return Math.min(n%10, find(n/10));
}
You can change the int by long ...
If you're interested in learning how to figure this out yourself (and you should be), I would try following these steps.
Do the process in your head, slowly - or even better, write the steps on paper! Take notice of each step you take.
Step one may be: look at the first digit
Consider the steps you've created. Are there parts which seem to be repeating themselves? These parts will likely be your recursive function.
Rewrite the steps as a recursive function (in plain English)
Translate the steps into your programming language; Java, in this case.
If you want, you can even leave the plain english steps in your code behind each line as comments, so everyone can easily follow your code
Personally I think a for loop would be quicker and easier than a recursive function. But for recursion or a for loop you need something to iterate on. Easiest way is to convert the number to a string and then iterate through it doing needed comparisons.
In your main:
int i = 578329;
String s = Integer.toString(i);
s = FindSmallest(s);
Call the function:
private String FindSmallest(String s){
if(s.length() <= 1)
return s;
String sFirstChar = s.substring(0,1);
String sSecondChar = s.substring(1,2);
int iFirst = Integer.parseInt(sFirstChar);
int iSecond = Integer.parseInt(sSecondChar);
if(iFirst < iSecond)
return FindSmallest( sFirstChar + s.substring(2));
else
return FindSmallest(sSecondChar + s.substring(2));
}
public static int find(int num) {
if(num < 10){
return num;
}
int d = num % 10;
int pmin = find(num / 10);
return (d <= pmin) ? d : pmin;
}
You can also write:
public static int minDigit(int n, int min){
if(n!=0) {
if(n%10 < min) {
min = n%10;
}
return minDigit(n/10, min);
}
return min;
}