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;
}
Related
public class a1 {
private static int unit = 0;
private static int sum = 0;
public static void main(String[] foo) {
unit = 10;
System.out.println(tailRecur(unit));
System.out.println(tailRecur2(10));
}
public static int tailRecur(int result) {
int sum = result + unit - 1;
unit = unit - 1;
if (unit == 0) {
return sum;
}
return tailRecur(sum);
}
public static int tailRecur2(int unit) {
if (unit == 0) return sum;
sum = sum + unit;
return tailRecur2(unit - 1);
}
}
I wrote a simple method to get achieve 1+...+10. I am not sure which one could be better with the meaning of recursion syntax. The all give me the right answer.
Storing static variables is unnecessary, so either solution isn't ideal.
Try thinking like this
What are you trying to do? Answer: 1+...+N.
What is the input? Answer: N, the highest number to sum to.
What can you do in each step recursively that will help you reach your answer with that input? Answer: Take that number and add it to the result of all N - 1 solutions.
When should you stop recursion and start accumulating the summation results (what's your base case)? Answer: When the number hits 1 (generally, the smallest possible input), or even less than it to prevent a negative number input from causing a StackOverflow error.
public static int sumUpTo(int x) {
if (x <= 1) return x;
return x + sumUpTo(x - 1);
}
I am working on the LeetCode question No.69 named sqrt(x)(https://leetcode.com/problems/sqrtx/). It asked me to return the square root of the integer also in another integer. Below is my solution.
public class Solution {
public int mySqrt(int x) {
int i = 0;
if(x==0)
{
return 0;
}
for(i = 1;i<x/2;i++)
{
if(((i*i)<=x)&&((i+1)*(i+1)>x))
{
break;
}
}
return i;
}
}
After I submit the code, all the test cases where x >= 2147395600 are all failed. When x = 2147395600, it is returning a 289398 instead of 46340, which is the right answer. What is the problem with my code?
You can try my code:
public int mySqrt(int x) {
long i = 0;
long j = x;
int mid = 0;
if (x == 0) {
return 0;
}
if (x == 1) {
return 1;
}
while (i <= j) {
mid = (int)(i + j)/2;
if (x/mid == mid) {
return (int)mid;
} else if (x/mid > mid) {
i = mid + 1;
} else if (x/mid < mid) {
j = mid - 1;
}
}
return (int)j;
}
Instead of int, use long. This is because int only goes up to 2147395600, while long goes much higher than that. However, the expense is that you would have to convert to long, then back to int.
I had the same problem but simply by add a typecast (long) in front of the ii expression, I solved it. The problem lay with the fact that ii was exceeding the limit of the value that can be held by int and hence a garbage value was being returned.
PS: This solution is super slow so do consider other solutions like Binary Search provided above.
You have declared i as an int and trying to do sqaure of i, which will throw error as int cannot hold such large values, use long to declare i or caste it i to long. But why do this when you can do it in O(log n) using Binary Search.
I'm making a small program that determines the minimum integer of 3 integers. I'm having problems returning the integers back into the variable answer.
Here Is how I imagine the program working;
PROGRAM RUNS:
Looks for Method called "Minimumum" with the listed argument.
Determines the minimum integer and returns it back to the method Minimum
This value gets stored in the answer variable
Code:
public class Method {
public static void main(String[] args) {
int answer = Minimum(20, 40, 50);
}
public static int Minimum(int first, int second, int third) {
if ((first < (second) && (first < third))) {
return first;
} else if ((second < (first) && (second < third))) {
return second;
} else if (((third < first) && (third < second))) {
return (third);
} else {
System.out.println("error");
}
}
}
You need to return a result in all cases, so your else block is incorrect. Do you really think there is a fourth case ? No, there isn't : there are three integers so the minimum is one of those three, meaning there only are 3 cases... Simply remove the else block. By the way, why do you use so many parentheses ? It's useless, and unreadable.
public static int Minimum(int first, int second, int third){
if (first < second && first < third)
return first;
else if (second < first && second < third)
return second;
else
return third;
}
As noted by the others, this is not sufficient to make your method correct. Indeed, you don't care about strict inequality here because when two numbers are the same, you can choose either of them as the minimum. This code breaks if the two first parameters are equal. To fix it, simply use <= instead of < (everywhere).
Your code looks a bit complicated.
int Minimum(int first, int second, int third) {
int min = first;
if (second < min) {
min = second;
}
if (third < min) {
min = third;
}
return min;
}
This looks creepy, but it should do it.
Hope it helps to understand.
You have to return in your final else block. But you could simplify your code with Math.min(int, int). Something like,
public static int Minimum(int first, int second, int third) {
return Math.min(first, Math.min(second, third));
}
Minimum function should always return the integer value in any case. After else, add return statement.
In Java 8+ your method could also look as follows:
public static int minimum(Integer val1, Integer val2, Integer val3){
List<Integer> list = Arrays.asList(new Integer[]{val1, val2, val3});
return list.stream().min((Integer v1, Integer v2) -> v1 < v2 ? 0 : 1 ).get();
}
I'm trying to solve this coding question:
Given an integer n, return the number of trailing zeroes in n!
Below is my code (codec this up using the wiki link)
public int trailingZeroes(int n) {
int count = 0, i = 5;
while(i<=n){
count+= n/i;
i*=5;
}
return count;
}
This runs for all test cases except when n = Integer.MAX_VALUE upon which I get a TLE. How can I fix this code to make it cover that test case. I have read about five articles on the net and everything seems to agree with my approach.
Much thanks.
So, I followed the long/BigInteger approach (thanks y'all):
public int trailingZeroes(int n) {
long count = 0;
for(long i= 5; n/i >= 1; i= i*5){
count+= n/i;
}
return (int)count;
}
As Iaune observed, your loop will never terminate when n is Integer.MAX_VALUE, because there is no int greater than that number (by definition). You should be able to restructure your loop to avoid that problem. For instance, this is the same basic approach, but flipped upside-down:
public int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n /= 5;
count += n;
}
return count;
}
You cannot write a for or while loop where the loop counter is an int and the upper limit is <= Integer.MAX_VALUE.
What happens with a simple increment (counter++) is that the loop counter is set to that value, the body executes and then the counter is incremented which results in a negative number, Integer.MIN_VALUE. And then everything happens all over again.
Other weird things may happen when the loop counter is incremented in quantities > 1 or (as here) is multiplied: the int loop counter just can't hold a value > Integer.MAX_VALUE
Consider another approach for iterating over these numbers. Or handle MAX_VALUE separately.
Your problem is that once i gets large enough (more than Integer.MAX_INT / 5) then the line i*=5; causes i to overflow to the "wrong" value. The value in question is 5 to the 14th power, which is 6103515625, but which overflows to 1808548329.
The result of this is that the loop just keeps executing forever. i will never become a value that's not <= Integer.MAX_INT, because there's just no such int.
To avoid this, you need i to be a larger data type than an int. If you change i and count in your original code to long, this will work fine. Of course, BigInteger would also work.
public class FactorialNumberTrailingZeros {
public static void main(String[] args) {
System.out.println(trailingZeroes(1000020));
}
private static int trailingZeroes(int n) {
int count = 0;
while (n > 0 && (n % 10 == 0)) {
n /= 10;
count ++;
}
return count;
}
}
public static void main(String[] args) {
int result = findFactorialTrailingZero(100);
System.out.println("no of trailing zeros are " + result);
}
public static int findFactorialTrailingZero(int no) {
int zeros = no / 5;
int zeroIncrementNo = 25;
int zerosIncrementFactor = 1;
int nextZeroIncrenent = 5;
for (int i = 1;no >= zeroIncrementNo; i++) {
zeros=zeros+zerosIncrementFactor;
zeroIncrementNo=25*(i+1);
if(i+1==nextZeroIncrenent){
zerosIncrementFactor++;
nextZeroIncrenent=nextZeroIncrenent*5;
}
}
return zeros;
/*
[n/5]+[n/25]+[n/125]+....
if n<25 then [n/5]
if n<125 then [n/5]+[n/25]
if n<625 then [n/5]+[n/25]+[n/125]
*/
#include<bits/stdc++.h>
#include<iostream>
using namespace std;
int countTrailingZeroes(int n)
{
int res=0;
for(int i=5;i<=n;i=i*5){
res=res+n/i;
}
return res;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int n;
cin>>n;
cout<<countTrailingZeroes(n);
return 0;
}
Output
25
6
Explanation:
25!=1.551121e+25 i.e contains 6 trailing zeroes
Here is my python code that could solve your problem:
def check(n):
j,ans=5,0
while j<=n:
ans=ans+n//j
j=j*5
return ans
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.