算法設計與分析HW1:LeetCode7

Description:

Reverse digits of an integer.

Example 1:

Input:123

Output:321


Example 2:

Input:-123

Output:-321


Note:

The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows

Subscribe to see which companies asked this question.

Solution:

1.判斷輸入是否爲0,若是,直接返回0

2.判斷輸入是否越界,若是,直接返回0

3.判斷整數是否正數,若否,跳到第6步,若是,設結果變量用於存儲當前所求結果,設輸入變量用於存儲輸入整數,跳第4步

4.先求輸入變量對10求模的結果,提取其個位數的數字,再將結果變量乘10,最後將輸入變量與結果變量相加,獲得當前的反轉結果

5.輸入變量除10,判斷是否>0,若是,跳回第4步,若否,跳第7步

6.取整數相反數,跳第3步

7.若判斷輸入整數大於0,返回結果變量;若輸入整數小於0,返回結果變量的相反數


代碼:

public class HW1 
{
	public static int reverseInteger(int x)
	{
		int result=0;
		int input=x;
		if(input==0)
			return result;
		if(input>java.lang.Integer.MAX_VALUE)
			return result;
		if(input>0)
		{
			int tmp1=0;
			int tmp2=0;
			while(input>0)
			{
				tmp1=result*10;
				tmp2=input%10;
				result=tmp1+tmp2;
				input=input/10;
				
			}
			return result;
		}
		else
		{
			return -reverseInteger(-x);
			
		}
	}
}


測試結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章