看板 Marginalman
無聊多寫一題 我居然沒寫過這個ㄟ== 而且我居然一次過 老天保佑 7. Reverse Integer Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 就把負的跟奇怪的都特殊處理 int reverse(int x) { int num_digits = 0; // deal with negative bool isneg = false; if(x<0) { if(x == INT_MIN) { return 0; } isneg = true; x = -x; } // calculate number of digits int tmp = x; while(tmp) { num_digits += 1; tmp = tmp/10; } // solve int ans = 0; bool check_overflow = (num_digits==10); vector<int> digit_max = {7, 4, 6, 3, 8, 4, 7, 4, 1, 2}; for(int i=num_digits-1; i>=0; i--) { int cur_digit = x%10; if(check_overflow) { if(cur_digit>digit_max[i]) { return 0; } else if (cur_digit<digit_max[i]){ check_overflow = false; } } ans += cur_digit*pow(10,i); x = x/10; } return isneg == 1 ? -ans : ans; } -- https://i.imgur.com/QaQrl0t.jpeg
https://i.imgur.com/yXpuYNA.jpeg
-- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.229.37.69 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1727106770.A.953.html
nozomizo: 大師 09/24 00:00