2015-02-17 78 views
3

如何反轉數字?整數的反轉數字

例1:X = 123,返回321 例題:X = -123,返回-321

這就是我的回答:

public int reverse(int x) { 
    int result = 0; 
    while(x != 0){ 
     result = result * 10 + x % 10; 
     x = x/10; 
    } 
    return result; 
} 

但是當我輸入1534236469,它將輸出1056389759,這是錯誤的。你對我的計劃有什麼看法?謝謝。

+1

,除非的Python代碼int是需要使用字符串作爲輸入。 1.如果存在,檢查減號刪除。 2.調用string.reverse()3.如果刪除它,則加上減號 – Nick 2015-02-17 23:31:54

回答

2

你可以寫X> 0(不雖然重要)也後你必須要考慮負數,我做了改變你的邏輯如下(也用很長很長,以避免溢出):

 long long reverse(long long x) 
     { 

      int sign = 1; 
      long long ans=0; 
      if(x < 0) 
      sign = -1; 
      x = abs(x); 
      while(x > 0) 
      { 
       ans *= 10; 
       ans += x%10; 
       x /=10; 
      } 
      return ans*sign; 
     } 
+0

OP的問題案例是一個正數。對於正數,你的代碼看起來與他的相同。它是否在'x = 1534236469'上產生了正確的結果? – jez 2015-02-17 23:15:54

+0

@jez也作爲OP在例子中給了一個負數我覆蓋了這種情況 – sashas 2015-02-17 23:17:57

+0

這和我的錯了 – 2015-02-17 23:19:32

0

爲什麼不能簡單地做:

while (x) 
    print x%10 
    x /= 10 

具有雙重符號轉換,如果x的值是原本負,以避免什麼MOD​​一個-ve數是個問題。

+0

非常好,但我需要返回一個數字 – 2015-02-17 23:53:47

5

一個原因你的程序不能得到正確的答案是,你 店resultint,但你希望能夠 扭轉號1534236469. 正確的答案應該是9646324351, 但這一數字大於一個int 的最大可能值,所以你最終得到了別的東西。 嘗試long long或嘗試使用不超過9位數字的輸入。


跟帖: 我建議long long,因爲這將相當可靠的給你 的8字節整數。您可能還會在long中獲得8個字節,具體取決於要構建代碼的 ,而在32位Windows上的Visual C++(例如) 只會給您4個字節。可能的話,4字節的長度很快就會適用於2字節的int,但是在這個時候,我們中的一些人仍然需要處理它。

+0

是的,但在OP的代碼 – aruisdante 2015-02-17 23:18:33

+0

中有一個大的跡象錯誤是的,你是對的,我知道這個數字超過了int類型,所以如何糾正它? – 2015-02-17 23:20:19

+0

使用「長」或相當於。但是,它仍然不會讓你的代碼適用於消極的nubmers。 – aruisdante 2015-02-17 23:21:15

1

Jason, 您應該將類​​型從int更改爲long。

public long reverse(long x) 
    { 
     long result = 0; 
     while (x != 0) 
     { 
      result = result * 10 + x % 10; 
      x = x/10; 
     } 
     return result; 
    } 
+1

這不適用於負數,這是OP輸入示例的一部分。 – aruisdante 2015-02-17 23:22:47

+1

這也取決於你運行的環境。在64位Linux上的g ++會給你8個字節的'long',Win32上的Visual C++會給你4個字節。 – 2015-02-17 23:24:37

+0

如果輸入的數字超過了long類型,我認爲它應該是錯誤的。我如何捕獲溢出,如果溢出返回0 – 2015-02-17 23:27:48

1

如何轉換爲字符串和反向?非常簡單:

int reverseDigits(int x) { 
     String s = Integer.toString(x); 
     for (int i = 0; i < s.length()/2; i++) { 
     char t = s[i]; 
     s[i] = s[s.length() - i - 1]; 
     s[s.length() - i - 1] = t; 
     } 
     return Integer.parseInteger(s); // subject to overflow 
    } 
0

您正在使用int來存儲數字,而數字超出了int的範圍。您在此問題中標記了算法。所以,更好的方法是使用鏈接列表。你可以更多地瞭解它。有很多顛倒鏈接列表的算法。

0

可以使用長型存儲結果

public int reverse(int x) { 
    long result = 0; 
    while (x != 0) { 
     result = result * 10 + x % 10; 
     x /= 10; 
    } 
    if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) 
     return 0; 
    return (int)result; 
} 
0

Schultz9999的回答的一個較短的版本:

int reverseDigits(int x) { 
    String s = Integer.toString(x); 
    s=new StringBuilder(s).reverse().toString(); 
    return Integer.parseInt(s); 
} 
0

這裏是反向號碼::

n=int(input('Enter the number:')) 
r=0 

while (n!=0):   
    remainder=n%10 
    r=remainder+(r*10) 
    n=n//10  

print('Reverse order is %d'%r)