4 Replies - 320 Views - Last Post: 26 January 2012 - 11:57 PM Rate Topic: -----

#1 curryjl  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 16
  • Joined: 02-March 09

Iteration problem

Posted 26 January 2012 - 04:15 PM

I am currently working on following problem http://projecteuler.net/problem=4. I have written the following code to solve the problem. For some reason when this "startNum = (startNum - 1000) + i;" code gets run I start getting some extremely small negative numbers. Can someone explain to me why this is happening?

import java.lang.StringBuffer;
public class Practice1 {
	public static void main(String[] args)
	{
		Practice1 x = new Practice1();
		int i = 2;
		int startNum = (999 * 998);
		boolean testLoop = true;
		while(testLoop)
		{
			if(x.isPalindrome(Integer.toString(startNum)))// if I don't make isPalindrome static 
			{
				System.out.println(startNum);
				testLoop = false;
				break;
			}
			System.out.println(startNum);
			startNum = (startNum - 1000) + i;
		}
		
		
	}
	
	public boolean isPalindrome(String pali)
	{
		String temp = new StringBuffer(pali).reverse().toString();
		if(pali == temp)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
}




Is This A Good Question/Topic? 1
  • +

Replies To: Iteration problem

#2 M4trixSh4d0w  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 79
  • Joined: 07-May 10

Re: Iteration problem

Posted 26 January 2012 - 04:28 PM

Because 999 * 998 = 997002. After 997 times of running that loop, your number goes negative. You are only adding 2,3,4 and subtracting 1000 each time.
Was This Post Helpful? 1
  • +
  • -

#3 curryjl  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 16
  • Joined: 02-March 09

Re: Iteration problem

Posted 26 January 2012 - 04:40 PM

I see the flaw in my logic now that you pointed that out. I am not even trying all the possible answers when going this route either. Thanks!
Was This Post Helpful? 0
  • +
  • -

#4 curryjl  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 16
  • Joined: 02-March 09

Re: Iteration problem

Posted 26 January 2012 - 11:54 PM

Finally got the answer :D... Just had to tell someone!
Was This Post Helpful? 0
  • +
  • -

#5 M4trixSh4d0w  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 79
  • Joined: 07-May 10

Re: Iteration problem

Posted 26 January 2012 - 11:57 PM

Nice Job. :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1