Reverse int golang - indexing

How to change 12345 to 54321?
With a string, you can change the string to a rune, and reverse it, but you cannot do the same for an integer. I have searched and found no one talking about this. Examples
131415 >>> 514131
1357 >>> 7531
123a >>> ERROR
-EDIT-
I was thinking, why not create a slice and index that?
Then I realized that you can't index int
(http://play.golang.org/p/SUSg04tZsc)
MY NEW QUESTION IS
How do you index an int?
OR
How do you reverse a int?

Here is a solution that does not use indexing an int
package main
import (
"fmt"
)
func reverse_int(n int) int {
new_int := 0
for n > 0 {
remainder := n % 10
new_int *= 10
new_int += remainder
n /= 10
}
return new_int
}
func main() {
fmt.Println(reverse_int(123456))
fmt.Println(reverse_int(100))
fmt.Println(reverse_int(1001))
fmt.Println(reverse_int(131415))
fmt.Println(reverse_int(1357))
}
Result:
654321
1
1001
514131
7531
Go playground

I converted the integer to a string, reverse the string, and convert the result back to a string.
package main
import (
"fmt"
"strconv"
)
func main() {
fmt.Println(reverse_int(123456))
fmt.Println(reverse_int(100))
fmt.Println(reverse_int(1001))
fmt.Println(reverse_int(131415))
fmt.Println(reverse_int(1357))
}
func reverse_int(value int) int {
intString := strconv.Itoa(value)
newString := ""
for x := len(intString); x > 0; x-- {
newString += string(intString[x - 1])
}
newInt, err := strconv.Atoi(newString)
if(err != nil){
fmt.Println("Error converting string to int")
}
return newInt
}

Very similar to the first answer but this checks to make sure you don't go out of bounds on the type.
func reverse(x int) int {
rev := 0
for x != 0 {
pop := x % 10
x /= 10
if rev > math.MaxInt32/10 || (rev == math.MaxInt32 /10 && pop > 7) {
return 0
}
if rev < math.MinInt32/10 || (rev == math.MinInt32/10 && pop < -8) {
return 0
}
rev = rev * 10 + pop
}
return rev
}

Also flips negative numbers int
func Abs(x int) int {
if x < 0 {
return -x
}
return x
}
func reverse_int(n int) int {
newInt := 0
sign := 1
if n < 0 {
sign = -1
}
n = Abs(n)
for n > 0 {
remainder := n % 10
newInt = newInt*10 + remainder
n /= 10
}
return newInt * sign
}
func main() {
fmt.Println(reverse_int(-100))
fmt.Println(reverse_int(-1001))
fmt.Println(reverse_int(131415))
fmt.Println(reverse_int(1357))
}

Similar to Fokiruna's answer but also checks for a 32bit overflow
func reverse(x int) int {
result, sign := 0, 1
if(x < 0) {
sign = -1
x = -x
}
for x > 0 {
remainder := x % 10;
result = result * 10 + remainder
x = x/10
}
var checkInt int = int(int32(result))
if checkInt != result {
return 0
}
return result * sign
}

Related

Determine whether number contains different digits

For a given number n, determine whether it contains different digits.
For example, 54 and 323 consist of different digits and 111 and 0 are the same.
you could try this
fun areDigitsDistinct(n:Int) = "$n".toCharArray().distinct().count() > 1
Try this:
fun hasDifferent(number: Int): Boolean {
val stringNumber = number.toString()
if (stringNumber.length == 1) return false
for (char in stringNumber) {
if (char != stringNumber[0]) return true
}
return false
}
Doesn't require convertion to String, doesn't require processing of all digits:
fun sameDigits(number: Int): Boolean {
val veryLastDigit = number % 10
var x = number / 10
while (x > 0) {
val lastDigit = x % 10
if (lastDigit != veryLastDigit) return false
x /= 10
}
return true
}
If you need to make it work with negative numbers too, change part before while-loop to this:
val _number = number.absoluteValue
val veryLastDigit = _number % 10
var x = _number / 10

How do I return from an anonymous recursive sub in perl6?

This does what I'd expect. fib(13) returns 233.
sub fib(Int $a --> Int) {
return 0 if $a == 0;
return 1 if $a == 1;
return fib($a -1) + fib($a -2);
}
my $square = -> $x { $x * 2 }; # this works with no return value
my #list = <1 2 3 4 5 6 7 8 9>.map( $square );
# returns [2 4 6 8 10 12 14 16 18]
I tried implementing fib() using an anonymous sub
my $fib = -> Int $x --> Int {
return 0 if $x == 0;
return 1 if $x == 1;
return $fib($x - 1) + $fib($x - 2);
}
$fib(13)
I get the following error when running that with explicit returns.
Attempt to return outside of any Routine
in block at test.p6 line 39
So I got rid of the return values.
my $fib = -> Int $x --> Int {
0 if $x == 0;
1 if $x == 1;
$fib($x - 1) + $fib($x - 2);
}
say $fib(13);
This last version never returns. Is there a way to write an anonymous recursive function without return values?
According to the documentation :
Blocks that aren't of type Routine (which is a subclass of Block) are
transparent to return.
sub f() {
say <a b c>.map: { return 42 };
# ^^^^^^ exits &f, not just the block }
The last statement is the implicit return value of the block
So you can try:
my $fib = -> Int $x --> Int {
if ( $x == 0 ) {
0; # <-- Implicit return value
}
elsif ( $x == 1 ) {
1; # <-- Implicit return value
}
else {
$fib($x - 1) + $fib($x - 2); # <-- Implicit return value
}
}
Three more options:
sub
You can write anonymous routines by using sub without a name:
my $fib = sub (Int $x --> Int) {
return 0 if $x == 0;
return 1 if $x == 1;
return $fib($x - 1) + $fib($x - 2);
}
say $fib(13); # 233
See #HåkonHægland's answer for why this (deliberately) doesn't work with non-routine blocks.
leave
The design anticipated your question:
my $fib = -> Int $x --> Int {
leave 0 if $x == 0;
leave 1 if $x == 1;
leave $fib($x - 1) + $fib($x - 2);
}
compiles. Hopefully you can guess that what it does -- or rather is supposed to do -- is exactly what you wanted to do.
Unfortunately, if you follow the above with:
say $fib(13);
You get a run-time error "leave not yet implemented".
My guess is that this'll get implemented some time in the next few years and the "Attempt to return outside of any Routine" error message will then mention leave. But implementing it has very low priority because it's easy to write sub as above, or write code as #HåkonHægland did, or use a case/switch statement construct as follows, and that's plenty good enough for now.
case/switch (when/default)
You can specify the parameter as $_ instead of $x and then you're all set to use constructs that refer to the topic:
my $fib = -> Int $_ --> Int {
when 0 { 0 }
when 1 { 1 }
$fib($_ - 1) + $fib($_ - 2)
}
say $fib(13); # 233
See when.
Blocks don't need to declare the return type. You can still return whatever you want, though. The problem is not in using return, it's in the declaration of the Int.
use v6;
my $fib = -> Int $x {
if $x == 0 {
0;
} elsif $x == 1 {
1;
} else {
$fib($x - 1) + $fib($x - 2);
}
}
say $fib(13) ;
The problem is that the return value needs to be the last executed. In the way you have done it, if it finds 0 or 1 it keeps running, getting to the last statement, when it will start all over again.
Alternatively, you can use given instead of the cascaded ifs. As long as whatever it returns is the last issued, it's OK.

In Go, scan numbers from a line using recursion

I want to scan a line of integers from stdin into a slice of integers. Each integer is separated by whitespace. Ther would be as many as N integers of user input. I'm trying not to use a for loop. For example,
1 15 16 17
So far, this is my function to perform the task,
var array []int
func read(b int) {
if b == 0 {
return
}
fmt.Scanf("%d", &array)
read(b - 1)
}
The idea is to read from the input, 1 15 16 17, and make it into a slice with value [1 15 16 17]
After compiling, I got the error,
Runtime error
For example,
package main
import "fmt"
var a []int
func read(b int) {
if b == 0 {
return
}
var i int
_, err := fmt.Scanf("%d", &i)
if err != nil {
return
}
a = append(a, i)
read(b - 1)
}
func main() {
read(4)
fmt.Println(a)
}
Input:
1 15 16 17<Enter>
Output:
[1 15 16 17]
Not recursive, but just reading integers until stdin is closed or something that can't be converted to an integer is read.
package main
import "fmt"
func main() {
var array []int
var i int
for {
_, err := fmt.Scan(&i)
if err != nil {
break
}
array = append(array, i)
fmt.Println("read number", i, "from stdin, array ", array)
}
}

Golang: int to slice conversion

Total golang (and programming) noob!
Given any six digit number, how could one output a slice where each character of that number is assigned an individual location within the slice?
For instance, a slice (let's call it s) containing all of these characters, would have s[0]=first digit, s[1]=second digit, s[2]=third digit and so on.
Any help would be greatly appreciated!
func IntToSlice(n int64, sequence []int64) []int64 {
if n != 0 {
i := n % 10
// sequence = append(sequence, i) // reverse order output
sequence = append([]int64{i}, sequence...)
return IntToSlice(n/10, sequence)
}
return sequence
}
The above answers are correct. Here comes another version of MBB's answer.
Avoiding recursion and efficient reverting may increase performance and reduce RAM consumption.
package main
import (
"fmt"
)
func reverseInt(s []int) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
func splitToDigits(n int) []int{
var ret []int
for n !=0 {
ret = append(ret, n % 10)
n /= 10
}
reverseInt(ret)
return ret
}
func main() {
for _, n := range splitToDigits(12345) {
fmt.Println(n)
}
}
https://play.golang.org/p/M3aOUnNIbdv
This is a two step process, first converting int to string, then iterating the string or converting to a slice. Because the built in range function lets you iterate each character in a string, I recommend keeping it as a string. Something like this;
import "strconv"
str := strconv.Itoa(123456)
for i, v := range str {
fmt.Println(v) //prints each char's ASCII value on a newline
fmt.Printf("%c\n", v) // prints the character value
}
I'm confused why nobody mentioned this way:
(No need recursion)
import (
"fmt"
"strconv"
)
func main() {
n := 3456
fmt.Println(NumToArray(n))
fmt.Println(NumToArray2(n))
}
func NumToArray(num int) []int {
arr := make([]int, len(strconv.Itoa(num)))
for i := len(arr) - 1; num > 0; i-- {
arr[i] = num % 10
num = int(num / 10)
}
fmt.Println(arr)
return arr
}
// Without converting to string
func NumToArray2(num int) (arr []int) {
for num > 0 {
arr = append(arr, num%10)
num = int(num / 10)
}
// Reverse array to the rigtht order
for i, j := 0, len(arr)-1; i < j; i, j = i+1, j-1 {
arr[i], arr[j] = arr[j], arr[i]
}
fmt.Println(arr)
return arr
}
P.S. Benchmarks are welcome
For this problem you can convert your int value to string and after that you can use split function which is under strings library.I hope below code will work for you!
package main
import (
"fmt"
"strings"
"strconv"
)
func main() {
num:=10101
a:=strconv.Itoa(num)
res:=strings.Split(a,"")
fmt.Println("The value of res is",res)
fmt.Printf("The type of res is %T\n",res)
fmt.Println(res[0])
}
Output: The value of res is [1 0 1 0 1]
The type of res is []string 1

How to print out the digits of an integer of any length?

This program is works as long as the divide variable is of the same base 10 power as the variable num, in this case the number is 12345 so divide needs to be 10000. While this works for 5 digit numbers, anything with more or less than 5 digits will not have their individual digits printed out. How do I configure divide to have be of the same base 10 power as num automatically?
public class lab5testing
{
public static void main (String args[])
{
int num = 12345, digit = 0, divide = 10000;
if (num != 0)
{
while(num != 0 )
{
digit = ((num/divide)%10);
System.out.println(digit);
divide /= 10;
if (divide == 0)
{
num = 0;
}
}
}
else
{
System.out.println(num);
}
}
}
Maybe you should try with this :
int length = (int)(Math.log10(num)+1);
and then :
int divide = Math.pow(10,lengh);