I have a code and I know that it isn't right. My task is "print all two-digit numbers which don't have two equal numbers". That means - program need to print numbers like 10, 12, 13 etc. Program didnt need to print 11 because there are 2 equal numbers. Hope that my program at least some is correct. (And sorry for my english).
public class k_darbs1 {
public static void main(String[] args) {
int a,b;
boolean notequal;
for(a = 10; a < 100; a++)
{
notequal = true;
for(b = 100; b < a; b++)
{
if(a != b)
{
notequal = false;
}
}
if(notequal == true)
{
System.out.println(a);
}
}
}
}
so why making things to much complex!?!!?!!!??
public static void main(String[] args) {
for(a = 10; a < 100; a++)
{
if(a%11==0){continue;}
System.out.println(a);
}
}
I think your making this slightly more complicated than it has to be. If n is a 2-digit number, then the leading digit is n/10 (integer division by 10) and the trailing digit is n%10 (modulo 10). You can just test if those two are unequal and print n as appropriate, there's no need for another for-loop.
For instance:
int n = 42;
System.out.println(n/10);
System.out.println(n%10);
4
2
Convert it to a string and check the characters.
for (int a = 10; a < 100; a++) {
String value = String.valueOf(a);
if (value.charAt(0) != value.charAt(1)) {
System.out.println(value);
}
}
You can parse Integer to String. Then compare the numbers with substring. For this process,
you need to know
Integer.toString(i);.
string.substring();
methods. This is not a very efficent way but it is a solution.
Related
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
The problem I'm trying to solve comes from ProjectEuler.
Some integers have following property:
n + reverse(n) = a number consisting entirely of odd digits.
For example:
14: 14 + 41 = 55
Numbers starting or ending with 0 aren't allowed.
How many of these "reversible" numbers are there below 10^9?
The problem also gives a hint:
there are 120 such numbers below 1000.
I'm quite new to Java, and I tried to solve this problem by writing a program that checks all the numbers up to a billion, which is not the best way, I know, but I'm ok with that.
The problem is that my program gives out a wrong amount of numbers and I couldn't figure out why! (The code will most likely contain some ugly things, feel free to improve it in any way)
int result = 0;
boolean isOdd = true;
boolean hasNo0 = true;
public int reverseNumber(int r) //this method should be working
{ //guess the main problem is in the second method
int n = 0;
String m = "";
if (r % 10 == 0) { hasNo0 = false; }
while (r > 0){
n = r % 10;
m = String.valueOf(m+n);
r /= 10;
}
result = Integer.parseInt(m);
return result;
}
public void isSumOdd(int max)
{
int number = 1;
int sum = 0;
Sums reverseIt = new Sums();
int amount = 0;
while (number <= max)
{
sum = reverseIt.reverseNumber(number) + number;
while (sum > 0)
{
int x = sum % 10;
if (x % 2 == 0) { isOdd = false; }
sum /= 10;
}
if (isOdd && hasNo0) { amount++; }
number++;
isOdd = true;
hasNo0 = true;
}
System.out.println(amount);
}
Called by
Sums first = new Sums();
first.reversibleNumbers(1000000000);
The most important problem in your code is the following line:
sum = reverseIt.reverseNumber(number) + number;
in isSumOdd(int max) function. Here the reverseIt object is a new instance of Sums class. Since you are using Sums member data (the boolean variables) to signal some conditions when you use the new instance the value of these member variables is not copied to the current caller object. You have to change the line to:
sum = this.reverseNumber(number) + number;
and remove the Sums reverseIt = new Sums(); declaration and initialization.
Edit: Attempt to explain why there is no need to instantiate new object instance to call a method - I've found the following answer which explains the difference between a function and a (object)method: https://stackoverflow.com/a/155655/25429. IMO the explanation should be enough (you don't need a new object because the member method already has access to the member data in the object).
You overwrite odd check for given digit when checking the next one with this code: isOdd = false;. So in the outcome you check only whether the first digit is odd.
You should replace this line with
idOdd = idOdd && (x % 2 == 0);
BTW. You should be able to track down an error like this easily with simple unit tests, the practice I would recommend.
One of the key problems here is that your reverseNumber method does two things: check if the number has a zero and reverses the number. I understand that you want to ignore the result (or really, you have no result) if the number is a multiple of 10. Therefore, you have two approaches:
Only send numbers into reverseNumber if they are not a multiple of 10. This is called a precondition of the method, and is probably the easiest solution.
Have a way for your method to give back no result. This is a popular technique in an area of programming called "Functional Programming", and is usually implemented with a tool called a Monad. In Java, these are implemented with the Optional<> class. These allow your method (which always has to return something) to return an object that means "nothing at all". These will allow you to know if your method was unable or unwilling to give you a result for some reason (in this case, the number had a zero in it).
I think that separating functionnalities will transform the problem to be easier. Here is a solution for your problem. Perhaps it isn't the best but that gives a good result:
public static void main(final String [] args) {
int counter = 0;
for (int i = 0; i < 20; i++) {
final int reversNumber = reverseNumber(i);
final int sum = i + reversNumber;
if (hasNoZeros(i) && isOdd(sum)) {
counter++;
System.out.println("i: " + i);
System.out.println("r: " + reversNumber);
System.out.println("s: " + sum);
}
}
System.out.println(counter);
}
public static boolean hasNoZeros(final int i){
final String s = String.valueOf(i);
if (s.startsWith("0") || s.endsWith("0")) {
return false;
}
return true;
}
public static int reverseNumber(final int i){
final StringBuilder sb = new StringBuilder(String.valueOf(i));
return Integer.parseInt(sb.reverse().toString());
}
public static boolean isOdd(final int i){
for (final char s : String.valueOf(i).toCharArray()) {
if (Integer.parseInt(String.valueOf(s))%2 == 0) {
return false;
}
}
return true;
}
the output is:
i: 12
r: 21
s: 33
i: 14
r: 41
s: 55
i: 16
r: 61
s: 77
i: 18
r: 81
s: 99
4
Here is a quick working snippet:
class Prgm
{
public static void main(String args[])
{
int max=(int)Math.pow(10, 3); //change it to (10, 9) for 10^9
for(int i=1;i<=max;i++)
{
if(i%10==0)
continue;
String num=Integer.toString(i);
String reverseNum=new StringBuffer(num).reverse().toString();
String sum=(new Long(i+Long.parseLong(reverseNum))).toString();
if(sum.matches("^[13579]+$"))
System.out.println(i);
}
}
}
It prints 1 number(satisfying the condition) per line, wc is word count linux program used here to count number of lines
$javac Prgm.java
$java Prgm
...//Prgm outputs numbers 1 per line
$java Prgm | wc --lines
120
I had an interview the other day that asked the question, loop through the numbers from 0 to 100 and print out every third number. This is a very easy question if you know what the modulo function is. So I came up with the solution (Note I was using Java):
for (int i=0; i<100; i++) {
if (i % 3 == 0) {
System.out.println(i);
}
}
He then asked, what if you can't use division or the modulo function. So I had to think about this for about 30 seconds, and came up with a solution, that I knew was very inefficient, and let him know it was very inefficient, but would work.
int x = 3;
for (int i=0; i<100; i++) {
for (int j=0; j<33; j++) {
if (x*j==i) {
System.out.println(i);
break;
}
}
}
I'm free writing this without testing, so it might not work 100%, but you get the idea of how I solved the problem. He said he understood what I was trying to do. He then said that there is another way to do it using a recursive function. He tried to briefly explain it to me, but I didn't understand how you could use a recursive function to solve this problem. Can anyone come up with a solution using recursion?
EDIT:
Thanks for all the answers! I didn't think this question would attract as much attention as it did, but I appreciate all the answers. Some of you didn't understand that you can ONLY increment by 1. So you must loop through every natural number from 0 to 100.
There is a cool trick to test if a number is divisible by three. If the sum of all its digits is divisible by three, then the original is divisible by three. This can be applied recursively: if I have a number a, I can add all the digits of a together to get b and see if b is divisible by 3. How do I know if b is divisible by three? Add all of its digits together to get c and see if c is divisible by three...
As with all recursion, you have to stop at some point. The base case is when you have a sum which is only one digit long- you can have a list of digits divisible by three and check against these. In code:
public boolean printDivisibleByThrees(){
for(int i=0; i<100; i++){
if(isDivisibleByThree(i)){
System.out.println(i);
}
}
}
public boolean isDivisibleByThree(int i){
if(i<0){
i = -1*i; //we only care about the absolute value of i
}
if(Arrays.asList(0,3,6,9).contains(i)){
return true;
} else if(i<10){
return false; //one digit number not divisible by three
} else {
int j = sumDigits(i);
return isDivisibleByThree(j);
}
}
public int sumDigits(int i){
String iString = (new Integer(i)).toString();
int sum = 0;
for(char digit : iString.toCharArray()){
sum += (new Integer(digit+"")).intValue();
}
return sum;
}
As no answer has been picked yet I like to add my two cents here.
Since the trick is do the modulo function with recursion and without division (as I understood) here is my solution:
public static void main(String[] args) {
for ( int i = 1; i <=100; i++ ){
if ( mod(i, 3) ){
System.out.println(i);
}
}
}
public static boolean mod(int a, int b){
if ( a < 0 ){
return false;
}else if (a==b){
return true;
}else{
return mod( a-b, b );
}
}
EDIT
This version will handle division by 0 and negative numbers on the modulo function:
public static boolean mod(int a, int b){
if ( b < 0 ){
b=b*-1;
}
if ( a < 0 || b == 0){
return false;
}else if (a==b){
return true;
}else{
return mod( a-b, b );
}
}
Use a second parameter that will keep if the number is or not the third
public class Rec
{
public static void rec(int n, int t) {
if(t==3) {
System.out.println(n);
t=0; // reset it
}
if(n!=100) {
rec(++n, ++t);
}
}
public static void main (String[] args)
{
rec(0, 3);
}
}
One can define the modulus operator using recursion as follows:
// Assume a, b > 0
static int mod(a, b) {
if (a < b) {
return a;
} else {
return mod(a-b, b);
}
}
So then you could do:
for (int i=0; i<100; i++) {
if (mod(i, 3) == 0) {
System.out.println(i);
}
}
I want to add one more answer that is probably unusual, but works fine for each range.
The code is C++ (I'm from mobile and I've only a C++ compiler on it), but it is quite easy to understand and to rewrite in Java.
#include <iostream>
void foo(int c, int n) {
static int i = 0;
if(c >= n) return;
switch(i++) {
case 1:
case 2:
foo(++c, n);
break;
case 0:
case 3:
std::cout << c << std::endl;
i = 1;
foo(++c, n);
}
}
int main() {
foo(0, 100);
}
Another variation on the recursion (JavaScript code):
function f(m,i){
if (i == 100){
return;
} else if (i == 3*m){
console.log(i);
f(m + 1,i + 1);
} else {
f(m,i + 1);
}
}
f(0,0);
Why not just do:
for (int i = 0; i < 100; i += 3)
System.out.println(i);
This way you don't have to check if it is every third number, because it goes up by 3 each time.
void printNth(int max, int n, int i, int sinceLastPrinted) {
if (i>max) {
return;
}
if (sinceLastPrinted == n-1) {
System.out.println(i);
sinceLastPrinted = -1;
}
printNth(max, n, i+1, sinceLastPrinted+1);
}
printNth(100, 3, 0, 0);
It's also not 100% clear whether the last number (100 in the example) should be included (if it is "a 3rd number"), depending on that you might need to modify to:
if (i>=max) {
And also not very clear where to start the "every 3rd"? 0, 3, 6, or 2, 5, 8? The advantage of my function is that this can be easily modified by passing different value for i
This would work. !
public class Recursion {
public static void main(String[] args) {
myRecursiveMethod(0,1,100,3);
}
public static void myRecursiveMethod(int begin,int temp,int end,int n)
{
if(begin<=end)
{
if(temp==n)
{
System.out.println(begin);
temp=0;
}
myRecursiveMethod(++begin,++temp,end,n);
}
}
}
So this probably would be easy if done like this
public static [] nums(int j)
{
int num = 12345;
int[]thenums = [5];
for(int i=0; i<5; i++)
{
thenums[4-i] = num%10;
num = num/10;
}
return the nums
}
i get {1,2,3,4,5}
but for some reason if the number starts with a 0 then it does not work
how to make this work if the number were
int num = 02141;
thanks
EDIT: Doh... I'd completely forgotten about octal literals. That explains why the value is showing up differently. (02141 is treated as an octal literal; it's not the same value as 2141.)
However, it sounds like the OP wants to "remember" the number of leading zeroes in a number. There's no way of doing that as an integer, because it's just remembering a value. What's the difference between seeing "3" birds and seeing "0000003" birds?
If you have a number representation where the leading zeroes are important, you're not just talking about an integer quantity, which is all that an int represents.
Where are you getting your input from? It sounds like you should just be maintaining it as a string from the start.
If you always want 5 digits, that's easy to do - and your current code should do it (when amended to actually compile) - something like this:
public class Test
{
public static void main(String[] args)
{
int[] digits = getDigits(123);
for (int digit : digits)
{
System.out.print(digit); // Prints 00123
}
}
public static int[] getDigits(int value)
{
int[] ret = new int[5];
for (int i = 4; i >=0 ; i--)
{
ret[i] = value % 10;
value = value / 10;
}
return ret;
}
}
Now that's hard-coded to return 5 digits. If you don't know the number of digits at compile-time, but you will know it at execution time, you could pass it into the method:
public static int[] getDigits(int value, int size)
{
int[] ret = new int[size];
for (int i = size - 1; i >=0 ; i--)
{
ret[i] = value % 10;
value = value / 10;
}
// Perhaps throw an exception here if value is not 0? That would indicate
// we haven't captured the complete number
return ret;
}
What happens in your code is that 02141 is not the same as 2141; the first is octal (equivalent to 1121 decimal), while the second is 2141 decimal.
The relevant part of the Java Language Specification is JLS 3.10.1, specifically the grammar productions for DecimalNumeral and OctalNumeral.
I'm trying to write a code that converts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don't understand.
What's wrong with that? Any other suggestions? I'd like to learn and hear for any comments for fixing it. Thank you.
public class NumberConverte {
public static void main(String[] args) {
int i = Integer.parseInt(args);
public static void Binary(int int1){
System.out.println(int1 + "in binary is");
do {
System.out.println(i mod 2);
} while (int1>0);
}
}
}
The error messages:
The method parseInt(String) in the type Integer is not applicable for the arguments (String[])
Multiple markers at this line
Syntax error on token "(", ; expected
Syntax error on token ")", ; expected
void is an invalid type for the variable Binary
Multiple markers at this line
Syntax error on token "mod", invalid AssignmentOperator
Syntax error on token "mod", invalid AssignmentOperator.
Integer.toBinaryString(int) should do the trick !
And by the way, correct your syntax, if you're using Eclipse I'm sure he's complaining about a lot of error.
Working code :
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
toBinary(i);
}
public static void toBinary(int int1){
System.out.println(int1 + " in binary is");
System.out.println(Integer.toBinaryString(int1));
}
}
Maybe you don't want to use toBinaryString(). You said that you are learning at the moment, so you can do it yourself like this:
/*
F:\>java A 123
123
1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0
*/
public class A {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]);
System.out.println(a);
int bit=1;
for(int i=0; i<32; i++) {
System.out.print(" "+(((a&bit)==0)?0:1));
bit*=2;
}
}
}
I suggest you get your program to compile first in your IDE. If you are not using an IDE I suggest you get a free one. This will show you where your errors are and I suggest you correct the errors until it compiles before worring about how to improve it.
There are a two main issues you need to address:
Don't declare a method inside another method.
Your loop will never end.
For the first, people have already pointed out how to write that method. Note that normal method names in java are usually spelled with the first letter lowercase.
For the second, you're never changing the value of int1, so you'll end up printing the LSB of the input in a tight loop. Try something like:
do {
System.out.println(int1 & 1);
int1 = int1 >> 1;
} while (int1 > 0);
Explanation:
int1 & 1: that's a binary and. It "selects" the smallest bit (LSB), i.e. (a & 1) is one for odd numbers, zero for even numbers.
int1 >> 1: that's a right shift. It moves all the bits down one slot (>> 3 would move down 3 slots). LSB (bit 0) is discarded, bit 1 becomes LSB, bit 2 becomes bit one, etc... (a>>0) does nothing at all, leaves a intact.
Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. You're outputting in reverse. To fix that, you'll probably be better off with a for loop, checking each bit from MSB to LSB.
The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. Something like this
for (i=31; i>=0; i--) {
if (int1 & (1<<i)) {
// i-th bit is set
System.out.print("1");
} else {
// i-th bit is clear
System.out.print("0");
}
}
1<<i is a left shift. Similar to the right shift, but in the other direction. (I haven't tested this at all.)
Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes.
For starters you've declared a method inside a method. The main method is the method that runs first when you run your class. ParseInt takes a string, whereas args is an Array of strings, so we need to take the first (0-based) index of the array.
mod is not a valid operator, the syntax you wanted was %
You can use System.out.print to print on the same line rather than println
Try these corrections and let me know how you get on:
public class NumberConverter {
public static void main(String[] args) {
int i = Integer.parseInt(args[0]);
Binary(i);
}
public static void Binary(int int1){
System.out.println(int1 + " in binary is ");
do {
System.out.print(int1 % 2);
int1 /= 2;
} while (int1 > 0);
}
}
Here is a small bittesting code I made for Android.
int myres = bitTest(7, 128);
public int bitTest(int bit,int value)
{
int res = 0;
int i = 0;
while (i <= bit) {
res = (value & 1);
value = value >> 1;
i++;
}
return res;
}
Best Regards
Mikael Andersson
StringBuffer sb = new StringBuffer("");
void breakNumber(int num){
if(num == 0 || num == 1){
System.out.println(num);
}else{
int modr = num % 2;
sb.append(modr);
int divr = num / 2;
if(divr > 1){
breakNumber(divr);
}else{
sb.append(modr);
StringBuffer sbr =sb.reverse();
System.out.println(sbr.toString());
}
}
}
package gg;
import java.util.*;
public class Gg {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = true;
while (flag) {
menu();
int n = in.nextInt();
switch (n) {
case 1:
System.out.println("enter an integer decimal number : ");
int d = in.nextInt();
System.out.print("the answer is ");
DTB(d);
System.out.println();
break;
case 2:
System.out.println("enter a binary number : ");
int b = in.nextInt();
System.out.print("the answer is " + BTD(b));
System.out.println();
break;
case 3:
flag = false;
break;
}
}
}
public static void menu() {
System.out.println("1.convert decimal to binary : ");
System.out.println("2.convert binary to decimal : ");
System.out.println("3.exit");
}
public static void DTB(int x) {
int n = 0;
int y = x;
while (y > 0) {
y /= 2;
n++;
}
int s[] = new int[n];
int i = 0;
while (x > 0) {
s[i] = x % 2;
x /= 2;
i++;
}
for (int j = s.length - 1; j >= 0; j--) {
System.out.print(s[j]);
}
}
public static int BTD(int x) {
int y = 2;
int sum = 0;
double k = 1;
int c = 0;
while (x > 0) {
double z = x % 10;
x /= 10;
k = Math.pow(y, c);
c++;
k *= z;
sum += k;
}
return sum;
}
}