I added these 3 variable to make operation of finding the winner in O(1) time.
private final int[] rowSum, colSum;
private int diagSum;
private int revDiagSum;
rowSum array contains sum of each row in n * n board, similary colSum contains column sums and diagSum and revDiagSum contains sum in diagonal and reverse diagonal.
Min-Max logic :
// returns an array containing { x, y, score }
// n is board.size here.
private int[] minMax(int player, final int n) {
// At max level --> human's turn | At min level --> Computer's turn
// MIN == -1 | MAX == +1
int best[] = null;
if(player == MIN) {
best = new int[] {-1, -1, Integer.MAX_VALUE};
}
else if(player == MAX) {
best = new int[] {-1, -1, Integer.MIN_VALUE};
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(board.get(i, j) == 0) {
int win = tryMove(i, j, player);
int []score = null;
if((win != 0) || board.filled()) {
// if this is the last move we can play in game, score is calculated.
score = new int[] {i, j, win};
}
else {
score = minMax(-1 * player, n);
}
undoMove(i, j, player);
if(player == MIN) {
if(score[2] < best[2]) {
best[0] = i;
best[1] = j;
best[2] = score[2];
}
}
else if(player == MAX) {
if(score[2] > best[2]) {
best[0] = i;
best[1] = j;
best[2] = score[2];
}
}
}
}
}
// return the optimal move(with score) player(=computer/human) can play by making a move.
return best;
}
private int tryMove(int i, int j, int player) {
int n = board.getSize();
board.set(i, j, player);
rowSum[i] += player;
colSum[j] += player;
if(i == j)
diagSum += player;
if(i + j == n - 1)
revDiagSum += player;
// if any of the sum == (+n / -n) means player won.
if(rowSum[i] == Math.abs(n) || colSum[j] == Math.abs(n) || diagSum == Math.abs(n) || revDiagSum == Math.abs(n)) {
return player;
}
return 0;
}
private int undoMove(int i, int j, int player) {
int n = board.getSize();
board.set(i, j, 0);
rowSum[i] -= player ;
colSum[j] -= player;
if(i == j)
diagSum -= player;
if(i + j == n - 1)
revDiagSum -= player;
return 0;
}
I call the above Min-Max func() always like this :
int[] move = minMax(-1, n); // always consider computer as the min-player and human as max player.
Now the issue I am facing is, whenever I am running this Game, I
("Human") am able to beat the computer which should not happen in the
ideal case as PC plays optimal moves everytime against us.
Tried debugging, but couldn't figure what's the issue here.
As per the logic, I am not able to suspect the issue in code.
Complete Code: https://github.com/tusharRawat821/Tic-Tac-Toe
Bug Fixed:
Below piece of code should be updated:
if(rowSum[i] == Math.abs(n) || colSum[j] == Math.abs(n) || diagSum == Math.abs(n) || revDiagSum == Math.abs(n)) {
....}
Corrected if condition :
if(Math.abs(rowSum[i]) == n || Math.abs(colSum[j]) == n || Math.abs(diagSum) == n || Math.abs(revDiagSum) == n) {
....}
The problem is:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?
Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).
The solution from the website I search is:
public class Solution {
public static int reverse(int x) {
int ret = 0;
boolean zero = false;
while (!zero) {
ret = ret * 10 + (x % 10);
x /= 10;
if(x == 0){
zero = true;
}
}
return ret;
}
public static void main(String[] args) {
int s = 1000000003;
System.out.println(reverse(s));
}
}
However when s = 1000000003, the console prints -1294967295 instead of 3000000001. So this solution still does not solve the overflow problem if we cannot use exception. Any help here?(Although there is a hint: add an extra parameter, I still cannot figure out what parameter I should add)
There's no need for any data type other than int.
Just make sure when there's an operation that increases a number, reversing the operation should give you the previous number. Otherwise, there's overflow.
public int reverse(int x) {
int y = 0;
while(x != 0) {
int yy = y*10 + x%10;
if ((yy - x%10)/10 != y) return 0;
else y = yy;
x = x/10;
}
return y;
}
Above most of the answers having a trivial problem is that the int variable possibly might overflow. You can try this : x = -2147483648 as parameter.
There has an easy way to solve the problem. Convert x to long, and check if the result >= Integer.MAX_VALUE, otherwise return 0.
The solution passed all test cases on https://leetcode.com/problems/reverse-integer/
This is a java version.
public int reverse(int x) {
long k = x;
boolean isNegtive = false;
if(k < 0){
k = 0 - k;
isNegtive = true;
}
long result = 0;
while(k != 0){
result *= 10;
result += k % 10;
k /= 10;
}
if(result > Integer.MAX_VALUE) return 0;
return isNegtive ? 0 - ((int)result) : (int)result;
}
C# version
public int Reverse(int x)
{
long value = 0;
bool negative = x < 0;
long y = x;
y = Math.Abs(y);
while (y > 0)
{
value *= 10;
value += y % 10;
y /= 10;
}
if(value > int.MaxValue)
{
return int.MaxValue;
}
int ret = (int)value;
if (negative)
{
return 0 - ret;
}
else
{
return ret;
}
}
Python version
def reverse(self, x):
isNegative = x < 0
ret = 0
x = abs(x)
while x > 0:
ret *= 10
ret += x % 10
x /= 10
if ret > 1<<31:
return 0
if isNegative:
return 0 - ret
else:
return ret
This java code handles the overflow condition:
public int reverse(int x) {
long reverse = 0;
while( x != 0 ) {
reverse = reverse * 10 + x % 10;
x = x/10;
}
if(reverse > Integer.MAX_VALUE || reverse < Integer.MIN_VALUE) {
return 0;
} else {
return (int) reverse;
}
}
This is an old question, but anyway let me have a go at it too! I just solved it on leetcode. With this check, you never hit the overflow/ underflow in either direction, and I think the code is more concise than all the listed codes. It passes all test cases.
public int reverse(int x) {
int y = 0;
while(x != 0) {
if(y > Integer.MAX_VALUE/10 || y < Integer.MIN_VALUE/10) return 0;
y *= 10;
y += x % 10;
x /= 10;
}
return y;
}
you can try this code using strings in java
class Solution {
public int reverse(int x) {
int n = Math.abs(x);
String num = Integer.toString(n);
StringBuilder sb = new StringBuilder(num);
sb.reverse();
String sb1;
sb1 = sb.toString();
int foo;
try {
foo = Integer.parseInt(sb1);
}
catch (NumberFormatException e){
foo = 0;
}
if(x < 0){
foo *= -1;
}
return foo;
}
}
My soluton for this problem is to convert integer inputed to c-string, then everthing will be easy.
class Solution {
public:
int reverse(int x) {
char str[11];
bool isNegative = false;
int i;
int ret = 0;
if ( x < 0 ) {
isNegative = true;
x = -x;
}
i = 0;
while ( x != 0 ) {
str[i++] = x % 10 + '0';
x = x / 10;
}
str[i] = '\0';
if ( (isNegative && strlen(str) == 10 && strcmp(str, "2147483648") > 0) || (!isNegative && strlen(str) == 10 && strcmp(str, "2147483647") > 0) ) {
cout << "Out of range!" << endl;
throw new exception();
}
i = 0;
int strLen = (int)strlen(str);
while ( str[i] != '\0' ) {
ret += ((str[i] - '0') * pow(10.0, strLen - 1 - i));
i++;
}
return (isNegative ? -ret : ret);
}
};
This works:
public class Solution {
public int reverse(int x) {
long tmp = Math.abs((long)x);
long res = 0;
while(tmp >= 10){
res += tmp%10;
res*=10;
tmp=tmp/10;
}
res+=tmp;
if(x<0){
res = -res;
}
return (res>Integer.MAX_VALUE||res<Integer.MIN_VALUE)? 0: (int)res;
}
}
I tried to improve the performance a bit but all I could come up with was this:
public class Solution {
public int reverse(int x) {
long tmp = x;
long res = 0;
if(x>0){
while(tmp >= 10){
res += tmp%10;
res*=10;
tmp=tmp/10;
}
}
else{
while(tmp <= -10){
res += tmp%10;
res*=10;
tmp=tmp/10;
}
}
res+=tmp;
return (res>Integer.MAX_VALUE||res<Integer.MIN_VALUE)? 0: (int)res;
}
}
Its C# equivalent runs 5% faster than the 1st version on my machine, but their server says it is slower, which can't be - I got rid of extra function call here, otherwise it is essentially the same. It places me between 60-30% depending on the language (C# or Java). Maybe their benchmarking code is not very good - if you submit several times - resulting times vary a lot.
Solution In Swift 4.0 (in reference to problem from https://leetcode.com/problems/reverse-integer/description/)
func reverse(_ x : Int) -> Int {
var stringConversion = String(x)
var negativeCharacter = false
var finalreversedString = String()
let signedInt = 2147483647 //Max for Int 32
let unSignedInt = -2147483647 // Min for Int 32
if stringConversion.contains("-"){
stringConversion.removeFirst()
negativeCharacter = true
}
var reversedString = String(stringConversion.reversed())
if reversedString.first == "0" {
reversedString.removeFirst()
}
if negativeCharacter {
finalreversedString = "-\(reversedString)"
} else {
finalreversedString = reversedString
}
return (x == 0 || Int(finalreversedString)! > signedInt || Int(finalreversedString)! < unSignedInt) ? 0 : Int(finalreversedString)!
}
Last night, i have tried this same problem and i have found a simple solution in python, which is given below, here after checking the number type positive or negative, though i have tried in different section for both of them, i have convert the negative number into positive and before returning the reverse number, i had converted the number into negative.
For handling overflow, i have just simply checked with the upper limit of our 32-bit signed number and lower limit of the number, and it accepted my answer, thank you.
class Solution:
def reverse(self, x: int):
reverse = 0
if x > 0:
while x != 0:
remainder = x % 10
if reverse > (2147483647/10):
return 0
reverse = reverse * 10 + remainder
x = int(x / 10)
return reverse
elif x < 0:
x = x * (-1)
while x != 0:
remainder = x % 10
if reverse > ((2147483648)/10):
return 0
reverse = reverse * 10 + remainder
x = int(x / 10)
reverse = reverse * (-1)
return reverse
else:
return 0
public static int reverse(int x) {
boolean pos = x >= +0;
int y = (pos) ? x : -x;
StringBuilder sb = new StringBuilder(
String.valueOf(y));
sb.reverse();
int z = Integer.parseInt(sb.toString());
return pos ? z : -z;
}
public static void main(String[] args) {
for (int i = -10; i < 11; i++) {
System.out.printf("%d r= '%d'\n", i, reverse(i));
}
}
Outputs
-10 r= '-1'
-9 r= '-9'
-8 r= '-8'
-7 r= '-7'
-6 r= '-6'
-5 r= '-5'
-4 r= '-4'
-3 r= '-3'
-2 r= '-2'
-1 r= '-1'
0 r= '0'
1 r= '1'
2 r= '2'
3 r= '3'
4 r= '4'
5 r= '5'
6 r= '6'
7 r= '7'
8 r= '8'
9 r= '9'
10 r= '1'
Did you notice the reverse of 10 and -10? Or 20? You could just return a String, for example
public static String reverse(int x) {
boolean pos = x >= +0;
int y = (pos) ? x : -x;
StringBuilder sb = new StringBuilder(
String.valueOf(y));
sb.reverse();
if (!pos) {
sb.insert(0, '-');
}
return sb.toString();
}
public static void main(String[] args) {
for (int i = -10; i < 11; i++) {
System.out.printf("%d r= '%s'\n", i, reverse(i));
}
}
Works as I would expect.
If you are required to return a 32 bit int, and still need to know if there was an overflow perhaps you could use a flag as an extra parameter. If you were using c or c++ you could use pointers to set the flag, or in Java you can use an array (since Java objects pass by value).
Java example:
public class Solution {
public static int reverse(int x, Boolean[] overflowed) {
int ret = 0;
boolean zero = false;
boolean inputIsNegative = x < 0;
while (!zero) {
ret = ret * 10 + (x % 10);
x /= 10;
if(x == 0){
zero = true;
}
}
//Set the flag
if ( (inputIsNegative && (ret > 0)) || ((!inputIsNegative) && (ret < 0)))
overflowed[0] = new Boolean(true);
else
overflowed[0] = new Boolean(false);
return ret;
}
public static void main(String[] args) {
int s = 1000000004;
Boolean[] flag = {null};
System.out.println(s);
int n = reverse(s,flag); //reverse() will set the flag.
System.out.println(flag[0].booleanValue() ? "Error: Overflow": n );
}
}
Notice if the reversed number is too large for a 32 bit integer the flag will be set.
Hope this helps.
Use string to store the reverse and then print or use long or BigInt
public class Solution {
/**
* OVERFLOW
* #param x
* #return
*/
public int reverse(int x) {
int sign = x>0? 1: -1;
x *= sign;
int ret = 0;
while(x>0) {
ret *= 10;
if(ret<0 || x>10&&ret*10/10!=ret) // overflow
return 0;
ret += x%10;
x /= 10;
}
return ret*sign;
}
public static void main(String[] args) {
assert new Solution().reverse(-2147483412)==-2147483412;
}
}
public class Solution {
public int Reverse(int x) {
var sign = x < 0 ? -1 : 1;
var reverse = 0;
if (x == int.MinValue)
{
return 0;
}
x = Math.Abs(x);
while(x > 0)
{
var remainder = x % 10;
if (reverse > ((int.MaxValue - remainder)/10))
{
return 0;
}
reverse = (reverse*10) + remainder;
x = x/10;
}
return sign * Convert.ToInt32(reverse);
}
}
Here we will use long to handle the the over flow:
public class Solution {
public int reverse(int A) {
// use long to monitor Overflow
long result = 0;
while (A != 0) {
result = result * 10 + (A % 10);
A = A / 10;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) {
return 0;
} else {
return (int) result;
}
}
}
Well This Suitable Code in Java Can be:-
public class Solution {
public int reverse(int x) {
int r;
long s = 0;
while(x != 0)
{
r = x % 10;
s = (s * 10) + r;
x = x/10;
}
if(s >= Integer.MAX_VALUE || s <= Integer.MIN_VALUE) return 0;
else
return (int)s;
}
}
My solution without using long:
public class ReverseInteger {
public static void main(String[] args) {
int input = Integer.MAX_VALUE;
int output = reverse(input);
System.out.println(output);
}
public static int reverse(int x) {
int remainder = 0;
int result = 0;
if (x < 10 && x > -10) {
return x;
}
while (x != 0) {
remainder = x % 10;
int absResult = Math.abs(result);
int maxResultMultipliedBy10 = Integer.MAX_VALUE / 10;
if (absResult > maxResultMultipliedBy10) {
return 0;
}
int resultMultipliedBy10 = absResult * 10;
int maxRemainder = Integer.MAX_VALUE - resultMultipliedBy10;
if (remainder > maxRemainder) {
return 0;
}
result = result * 10 + remainder;
x = x / 10;
}
return result;
}
}
here is the JavaScript solution.
/**
* #param {number} x
* #return {number}
*/
var reverse = function(x) {
var stop = false;
var res = 0;
while(!stop){
res = res *10 + (x % 10);
x = parseInt(x/10);
if(x==0){
stop = true;
}
}
return (res <= 0x7fffffff && res >= -0x80000000) ? res : 0
};
Taking care if the input is negative
public int reverse(int x)
{
long result = 0;
int res;
int num = Math.abs(x);
while(num!=0)
{
int rem = num%10;
result = result *10 + rem;
num = num / 10;
}
if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
{
return 0;
}
else
{
res = (int)result;
return x < 0 ? -res : res;
}
}
This solution in Java will work:
class Solution {
public int reverse(int x) {
long rev = 0, remainder = 0;
long number = x;
while (number != 0) {
remainder = number % 10;
rev = rev * 10 + remainder;
number = number / 10;
}
if (rev >= Integer.MAX_VALUE || rev <= Integer.MIN_VALUE || x >= Integer.MAX_VALUE || x <= Integer.MIN_VALUE)
return 0;
else
return (int) rev;
}
}
Much simpler solution. Ensure that intermittent result does not exceed INT_MAX or get below INT_MIN
int reverse(int x) {
int y = 0;
while(x != 0) {
if ( (long)y*10 + x%10 > INT_MAX || (long)y*10 + x%10 < INT_MIN) {
std::cout << "overflow occurred" << '\n'
return 0;
}
y = y*10 + x%10;
x = x/10;
}
return y;
}
Here is the solution coded in JS(Javascript, it has passed all the 1032 test cases successfully in Leetcode for the problem (https://leetcode.com/problems/reverse-integer), also as asked in the question about the same.
/**
* #param {number} x
* #return {number}
*/
var reverse = function(x) {
let oldNum = x, newNum = 0, digits = 0, negativeNum = false;
if(oldNum < 0){
negativeNum = true;
}
let absVal = Math.abs(x);
while(absVal != 0){
let r = Math.trunc(absVal % 10);
newNum = (newNum*10) + r; digits++;
absVal = Math.floor(absVal/10);
}
if( !(newNum < Number.MAX_VALUE && newNum >= -2147483648 && newNum <= 2147483647)){
return 0;
}
return negativeNum ? -newNum :newNum;
};
Here is the solution coded in JS(Javascript, it has passed all the 1032 test cases successfully in Leetcode for the problem (https://leetcode.com/problems/reverse-integer), also as asked in the question about the same.
/**
* #param {number} x
* #return {number}
*/
var reverse = function(x) {
let oldNum = x, newNum = 0, digits = 0, negativeNum = false;
if(oldNum < 0){
negativeNum = true;
}
let absVal = Math.abs(x);
while(absVal != 0){
let r = Math.trunc(absVal % 10);
newNum = (newNum*10) + r; digits++;
absVal = Math.floor(absVal/10);
}
if( !(newNum < Number.MAX_VALUE && newNum >= -2147483648 && newNum <= 2147483647)){
return 0;
}
return negativeNum ? -newNum :newNum;
};
The earlier answer was posted by the same user (unregistered). Consider this one.
There are several good solutions posted. Here is my JS solution:
const reverse = function (x) {
const strReversed = x.toString().split("").reverse().join("");
rv =
parseInt(strReversed) > Math.pow(2, 31)
? 0
: Math.sign(x) * parseInt(strReversed);
return rv;
};
I got all 1032 cases to work in python, I don't know how to remove multiple 0's such as 100, 1000, 10000 etc thus I used my if statement multiple times lol.
class Solution:
def reverse(self, x: int) -> int:
string = ""
y = str(x)
ab = list(reversed(y))
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if len(ab) > 1 and ab[0] == "0":
ab.remove("0")
if ab[-1] == "-":
ab.remove("-")
ab.insert(0, "-")
for i in ab:
string += i
if int(string) > 2**31 - 1 or int(string) < -2**31:
return 0
return string
public static int reverse(int x) {
if (x == 0) return 0;
int sum = 0;
int y = 0;
while (x != 0) {
int value = (x % 10);
x = x - value;
y = sum;
sum = (sum * 10) + value;
if(sum / 10 != y) return 0;
x = x / 10;
}
return sum;
}
Extracting the first digit and dividing x to ten until x will be equal to 0. Therefore integer will be tokenized its digits.
Every extracted value will be adding the sum value after multiplying the sum by 10. Because adding a new digit means that adding a new 10th to the sum value. Also added if block to check any corruption of data because after 9th digit data will be corrupted.
1032 / 1032 test cases passed.
Status: Accepted
Runtime: 3 ms
Memory Usage: 38 MB
Public int reverse(int A) {
int N, sum = 0;
int rem = 0;
boolean flag = false;
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;
if (A < 0) {
flag = true;
A = A * -1;} // 123 // 10 1
while (A > 0) {
rem = A % 10;
if (flag == true) {
if ((min + rem) / 10 > -sum) {
return 0;}}else{
if ((max - rem) / 10 < sum) {
return 0;}}
sum = (sum * 10) + rem;
A = A / 10;}
return (flag == true) ? —sum : sum;}}
#java #Algo
def reverse(self, x: int) -> int:
if x<=-2**31 or x>=2**31-1:
return 0
else:
result = 0
number = x
number = abs(number)
while (number) > 0:
newNumber = number % 10
result = result * 10 + newNumber
number = (number // 10)
if x<0:
result = "-"+str(result)
if int(result)<=-2**31:
return 0
return result
else:
if result>=2**31-1:
return 0
return result
if __name__ == '__main__':
obj = Solution()
print(obj.reverse(1534236469))
Note that there are previous solutions that do not work for input: 1000000045
try this:
public int reverse(int A) {
int reverse=0;
int num=A;
boolean flag=false;
if(A<0)
{
num=(-1)*A;
flag=true;
}
int prevnum=0;
while(num>0)
{
int currDigit=num%10;
reverse=reverse*10+currDigit;
if((reverse-currDigit)/10!=prevnum)
return 0;
num=num/10;
prevnum=reverse;
}
if(flag==true)
reverse= reverse*-1;
return reverse;
}
To clarify I only wanted one or two for loops to help me on my way, preferably in the same style as I had used in the vertical :)
I'm making a game using a 2D array, and I need a check that tests if at the current position (indicated by a green square) the character there is part of a diagonal sequence of "l" more of the character.
public static boolean diagonals(char[][] b, int row, int col, int l) {
int counter = 1; // because we start from the current position
char charAtPosition = b[row][col];
int numRows = b.length;
int numCols = b[0].length;
int topleft = 0;
int topright = 0;
int bottomleft = 0;
int bottomright = 0;
for (int i=row-1,j=col-1;i>=0 && j>=0;i--,j--) {
if (b[i][j]==charAtPosition) {
topleft++;
} else {
break;
}
}
for (int i=row-1,j=col+1;i>=0 && j<=numCols;i--,j++) {
if (b[i][j]==charAtPosition) {
topright++;
} else {
break;
}
}
for (int i=row+1,j=col-1;i<=numRows && j>=0;i++,j--) {
if (b[i][j]==charAtPosition) {
bottomleft++;
} else {
break;
}
}
for (int i=row+1,j=col+1;i<=numRows && j<=numCols;i++,j++) {
if (b[i][j]==charAtPosition) {
bottomright++;
} else {
break;
}
}
return topleft + bottomright + 1 >= l || topright + bottomleft + 1 >= l; //in this case l is 5
}
The idea is that we walk in four directions and count the steps. This may not be the most efficient implementation, but at least it looks neat and easy to understand.
Here's the function, it works. The explanation is in the comments in the code, but if you find anything confusing let me know and I'll explain it.
public static boolean diagonals(char[][] b, int row, int col, int l) {
int forwardCounter = 1; // this counts top right to bottom left
int backCounter = 1; // this counts top left to bottom right
int distance = 1;
// 0 = topleft, 1 = topright, 2 = bottomleft, 3 = bottomright
boolean[] checks = new boolean[]{true, true, true, true};
char charAtPosition = b[row][col];
while(checks[0] || checks[1] || checks[2] || checks[3]) {
for(int i = 0; i < 4; i++) {
if(checks[i]) {
// This looks confusing but it's simply just converting i into
// The four different directions
checks[i] = checkSquare(b, row + (i < 2 ? -distance : distance),
col + (i % 2 == 0 ? -distance : distance), charAtPosition);
if(checks[i]) {
// If top left or bottom right
if(i % 3 == 0) {
backCounter++;
} else {
forwardCounter++;
}
}
}
}
if (forwardCounter >= l || backCounter >= l) return true;
distance++;
}
return false;
}
private static boolean checkSquare(char[][] b, int row, int col, char check) {
if(row < 0 || row >= b.length) return false;
if(col < 0 || col >= b[0].length) return false;
return check == b[row][col];
}
It is possible to count the number of zeros in an integer through a recursive method that takes a single int parameter and returns the number of zeros the parameter has.
So:
zeroCount(1000)
Would Return:
3
You can remove the last digit from an integer by doing: "12345 / 10" = 1234
You can get the last digit from an integer by doing: "12345 % 10" = 5
This is what I have so far:
public static int zeroCount(int num)
{
if(num % 10 == 0)
return num;
else
return zeroCount(num / 10);
}
Does anyone have any suggestions or ideas for helping me solve this function?
public static int zeroCount(int num)
{
if(num == 0)
return 0;
if(num %10 ==0)
return 1 + zeroCount(num / 10);
else
return zeroCount(num/10);
}
this would work
Run through your code in your head:
zeroCount(1000)
1000 % 10 == 0, so you're going to return 1000. That doesn't make sense.
Just pop off each digit and repeat:
It sounds like homework, so I'll leave the actual code to you, but it can be done as:
zeroes(0) = 1
zeroes(x) = ((x % 10 == 0) ? 1 : 0) + zeroes(x / 10)
Note that without the terminating condition, it can recurse forever.
There are three conditions here:
1. If number is single digit and 0 , then return 1
2. If number is less than 10 i.e. it is a number 1,2,3...9 then return 0
3. call recursion for zeros(number/10) + zeros(n%10)
zeros(number){
if(number == 0 ) //return 1
if(number < 10) //return 0
else
zeros(number/10) + zeros(number%10)
}
n/10 will give us the n-1 digits from left and n%10 gets us the single digit.
Hope this helps!
Check this out for positive integers:
public static int zeroCount(int number) {
if (number == 0) {
return 1;
} else if (number <= 9) {
return 0;
} else {
return ((number % 10 == 0) ? 1 : 0) + zeroCount(number / 10);
}
}
it is a simple problem and you don't need to go for recursion
I think a better way would be converting the integer to a string and check for char '0'
public static int zeroCount(int num)
{
String s=Integer.toString(num);
int count=0;
int i=0;
for(i=0;i<s.length;i++)
{
if(s.charAt(i)=='0')
{
count++;
}
}
return count;
}
You have to invoke your recursive function from both if and else. Also, you were missing a Base Case: -
public static int zeroCount(int num)
{
if(num % 10 == 0)
return 1 + zeroCount(num / 10);
else if (num / 10 == 0)
return 0;
else
return zeroCount(num / 10);
}
import java.util.*;
public class Count
{
static int count=0;
static int zeroCount(int num)
{
if (num == 0){
return 1;
}
else if(Math.abs(num) <= 9)
{
return 0;
}
else
{
if (num % 10 == 0)
{ // if the num last digit is zero
count++;
zeroCount(num/10);
} // count the zero, take num last digit out
else if (num%10 !=0){
zeroCount(num/10);
}
}
return count;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Input: ");
int num = sc.nextInt();
System.out.println("Output: " +zeroCount(num));
}
}
public static int count_zeros(int n)
{
if(n<=9)
{
if(n==0)
{
return 1;
}
else
{
return 0;
}
}
int s=n%10;
int count=0;
if(s==0)
{
count=1;
}
return count+count_zeros(n/10);
}
int countZeros(int n){
//We are taking care of base case
if(n<=9){
if(n==0){
return 1;
}
else
{
return 0;
}
}
int last=n%10; //last element of number for e.g- 20403, then last will give 3
int count=0; //Initalsizing count as zero
if(last==0){ //We are checking either the last digit is zero or not if it will
will update count from 0 to 1
count=1;
}
return count+countZeros(n/10); //Recursive call
}
int check(int n){
if(n==0)
return 1;
return 0;
}
int fun(int n)
{
if(n/10==0)
{
if(n==0){
return 1;
}
else{
return 0;
}
}
return check(n%10)+fun(n/10);
}
Check this out, this is the solution I came up with.
int countZeros(int input){
//base case
if(input == 0){
return 1;
}
int count = 0;
int lastDigit = input%10;
if(lastDigit == 0){
count = 1;
}
//calc the smallInput for recursion
int smallInput = input/10;
//set smallAns = 0, if i/p itself is not 0 and no 0 is present then return smallAns = 0
int smallAns = 0;
//recursion call
if(smallInput != 0){
smallAns = countZerosRec(smallInput);
}
//if we get lastDigit = 0 then return smallAns + 1 or smallAns + count, else return smallAns
if(lastDigit == 0){
return smallAns+count;
}
else{
return smallAns;
}}
You know that x % 10 gives you the last digit of x, so you can use that to identify the zeros. Furthermore, after checking if a particular digit is zero you want to take that digit out, how? divide by 10.
public static int zeroCount(int num)
{
if(num == 0) return 1;
else if(Math.abs(num) < 9) return 0;
else return (num % 10 == 0) ? 1 + zeroCount(num/10) : zeroCount(num/10);
}
I use math.Abs to allow negative numbers, you have to import java.lang.Math;
static int cnt=0;
public static int countZerosRec(int input) {
// Write your code here
if (input == 0) {
return 1;
}
if (input % 10 == 0) {
cnt++;
}
countZerosRec(input / 10);
return cnt;
}
CPP Code using recursion:
int final=0;
int countZeros(int n)
{
if(n==0) //base case
return 1;
int firstn=n/10;
int last=n%10;
int smallop=countZeros(firstn);
if(last==0)
final=smallop+1;
return final;
}
int countZeros(int n)
{
if(n==0)
{
return 1;
}
if(n<10) // Needs to be java.lang.Math.abs(n)<10 instead of n<10 to support negative int values
{
return 0;
}
int ans = countZeros(n/10);
if(n%10 == 0)
{
ans++;
}
return ans;
}
public static int countZerosRec(int input){
// Write your code here
if(input == 0)
return 1;
if(input <= 9)
return 0;
if(input%10 == 0)
return 1 + countZerosRec(input/10);
return countZerosRec(input/10);
}