pull down to refresh
As a dev who rejects modernity and embrace tradition, this is my string based approach
public boolean isPalindrome(int x) {
String s = "" + x;
int l = s.length();
for(int i = 0;i < l;i++){
int j = l-1-i;
if (s.charAt(i)!=s.charAt(j)) return false;
}
return true;
}and integer based approach
private int reverse(int n){
int r = 0;
while(n != 0) {
int d = n % 10;
r = r * 10 + d;
n = n / 10;
}
return r;
}
public boolean isPalindrome(int x) {
if(x<0)return false;
return reverse(x)==x;
}reply
deleted by author
reply
reply
reply
reply
(defun print-palindrome-function ()
(println "public boolean isPalindrome(int x) {")
(println " String s = \"\" + x;")
(println " int l = s.length();")
(println " for (int i = 0; i < l; i++) {")
(println " int j = l - 1 - i;")
(println " if (s.charAt(i) != s.charAt(j)) return false;")
(println " }")
(println " return true;")
(println "}"))
(print-palindrome-function)never lol
reply
I found it was easier by looking through each methods subsequent methods after seeing the compile type mismatches.
i32->as_str()->bytes()(this is an iterator of bytes) ->rev()(this makes the iterator iterate in reverse) ->collect()(turns an iterator into a collection of the underlying type (bytes in this case).Overall, I got more of the sense with Rust that you can use the compiler to your advantage instead of trying to work around it. But, I think there will be more complex things where that won't work out and I might work myself into a corner where I'll have to do some contortion to get out.
fn main() {} pub fn is_palindrome(x: i32) -> bool { let x_str = x.to_string(); let reversed_bytes: Vec<u8> = x_str.as_str().bytes().rev().collect(); let reversed = match String::from_utf8(reversed_bytes) { Ok(reversed_str) => reversed_str, Err(err) => panic!("Problem getting string after reversed: {err:?}"), }; return reversed == x_str; } #[cfg(test)] mod tests { use super::*; #[test] fn test_example_1() { let x = 121; let answer = true; assert_eq!(is_palindrome(x), answer); } #[test] fn test_example_2() { let x = -121; let answer = false; assert_eq!(is_palindrome(x), answer); } #[test] fn test_example_3() { let x = 10; let answer = false; assert_eq!(is_palindrome(x), answer); } }